0
\$\begingroup\$

Hi I am using a for loop to check and see if my players character is colliding with a collision object in the game. But for some reason it only checks the last Rectangle of the list.

private void collisionDetection()
{
    for(Rectangle rectangle : colrect) {
        Rectangle rect2 = new Rectangle(posX, posY, 64, 64);
        if (rectangle.overlaps(rect2))
        {
            m.setTileCollision(true);
        }
        else
        {
            m.setTileCollision(false);
        }
    }
}

Why and how is this happening? I gave up on looking for an answer so I'm here. I want to check all of the Rectangles in the list not the last... I even for looped text through Bitmap font to see the positions and set text at all Rectangles and that works properly, but this doesn't. Another solution perhaps is in order?

\$\endgroup\$
3
\$\begingroup\$

This is because you are (presumably) overwriting the tileCollision boolean for every rectangle you check. Changing your if-statements to something like this might do the trick:

m.setTileCollision(false); // Do this OUTSIDE the for loop

// Then, inside the for loop...
if (rectangle.overlaps(rect2)) {
    m.setTileCollision(true);
    break; // No need to check the other rects, we already found a collision
}
// Remove else statement since it's no longer needed
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.