Faced a problem, I can not catch the collision of two rectangles. I tried to do this with intersects()
, but it requires two rectangles inside the method, and I only need to catch a collision with one rectangle. Here is what I write:
Iterator<Enemy> i = enemy.iterator(); while(i.hasNext()) { Enemy e = i.next(); if(((Ball) ball).getRect().intersects((e.getRect()))) { i.remove(); } }
I don’t know what it wants, it should work, in the lessons on YouTube I saw that one object was used there and everything was fine ... What was the problem with?
UPDATE:
It means so. Enemy
and Ball
are two classes; a score is a bullet that must kill the enemy, respectively, enemi is the enemy that the ball must kill. I need to catch the collision of these two objects, trying to catch using intersects
, which requires two rectangles, although in the video tutorial that I watched, the tutorial's narrator uses only one class object, the second is used to call the intersect, as in my code example. So the question is, how does its intersect differ from mine? Here is his lesson. Writing a 2D game on java - Part 7.
The error that gives me when I start to compile
The method intersects (Rect, Rect) in the type of the Rect (Rect)
UPDATE 2:
I found a way that solves my problem, maybe someone will come in handy. I almost completely modified the code, here’s what it looks like:
private void testCollision() { Iterator<Enemy> i = enemy.iterator(); Iterator<Ball> b = ball.iterator(); while(i.hasNext() && b.hasNext()) { Enemy enemies = i.next(); Ball balls = b.next(); if (Math.abs(balls.x - enemies.x) <= (balls.width + enemies.width) / 2f && Math.abs(balls.y - enemies.y) <= (balls.height + enemies.height) / 2f) { i.remove(); b.remove(); } } }
balls.x - enemies.x - the central border of our object.
UPDATE 3:
I open the topic again because I had a problem
"you need to return the iterator again to the first element, because it has already been driven by the previous pass to the last and hasNext () and returns false."
This is a quote from one person who tried to explain to me how to correct a mistake, but was never able to explain. Can someone tell me how to do this? The code I use is the same.
After reading this quote several times - my brain broke