Search code examples
javacollision

Collision code not working


I have these 'monsters' that are continually created and deleted when they reach the bottom of the screen. They move left and right and I want it so that when they touch (or if they are created ontop of eachother) one of them moves out of the way.

Currently I have in the class managing the monsters:

public void update() {
    int i = 0;
    while(i < (Constants.NUMBER_ENEMIES-2)) {
        if (Rect.intersects(npcManager.getList().get(i).getRectangle(), npcManager.getList().get(i + 1).getRectangle()))
            npcManager.getList().get(i).setRectangle(200);
        i += 1;
    }
}

Where npcManager is an instance and thelist it gets us an array list of the NPCs. The setRectangle method I created is:

public Rect setRectangle(int move) {
    rectangle.top += move;
    rectangle.bottom += move;
    return rectangle;
}

Where it should move the NPC down by 200 so that it is no longer colliding.

My question is, is there any reason why this code isn't working? Currently the rectangles just pass through eachtother and the code has no effect.


Solution

  • By looking at the number of enemies - 2 (when the number of enemies in this specific case was 2), the while loop never initiated and the code did not run.