Java Programmer
Java Programmer

Reputation: 205

LibGDX: Collision only works with one Rectangle

In my android game the collision works as long as I only have one rectangle in my Array, so it works with this:

rects = new Rectangle[1];
 for(int i = 0; i < rects.length; ++i)
  rects[i] = new Rectangle(i * 150, 0, 150, 150);

but not if I add another rectangle rects = new Rectangle[2];

My collision code looks like this:

public boolean collision(Rectangle rect){
 return (Intersector.overlaps(playerBound, rect));
}

and I use it like this:

for(int i = 0; i < rects.length; ++i){
 if(!collision(rects[i]))
  player.setY(player.getY() - 1f);
}

playerBound is initialized like this: playerBound = new Rectangle(player.getX(), player.getY(), player.getWidth(), player.getHeight() + 1);

What is the problem? I don't understand how it can work if there's only one rectangle in the array but not if there's more.

Upvotes: 0

Views: 161

Answers (1)

noone
noone

Reputation: 19776

Well, that's because there is a logical error in this code snippet here:

for(int i = 0; i < rects.length; ++i){
    if(!collision(rects[i]))
        player.setY(player.getY() - 1f);
}

You check more than one rectangle for collision. Let's assume that the first one in the array will cause a collision. Fine, the Y won't change. Now there is another rect. This second rect will not cause a collision. What happens now? You change the player's Y value even though there has been a collision.

Change it to something like this:

boolean collision = false;
for(int i = 0; i < rects.length; ++i){
    if(collision(rects[i]))
        collision = true;
}

if (collision == false)
    player.setY(player.getY() - 1f);

Upvotes: 1

Related Questions