Search code examples
javaarraylistlibgdxcollision-detectionrectangles

Java ArrayList first item collision doesn't work, but without it works


I am creating an ArrayList items of Rectangles:

private ArrayList<Rectangle> items = new ArrayList<>();

I use the ArrayList in my update method.

@Override
public void update(float delta) {

    items.add(new Rectangle(GameWorld.obstacle1.getX() - GameRenderer.generator2.getValue2(),
                GameWorld.obstacle1.getY() + GameRenderer.generator2.getValue1() , 5, 5));

        if (Intersector.overlaps(GameWorld.wizard.getBoundingRectangle(), items.get(0))) {                
            Gdx.app.exit();             
        }    
}

The collision with the item does not work, because the program doesn't close when it hits the item.

But when I do it like this, it works perfectly fine:

private Rectangle doublepoints;

doublepoints = new Rectangle(GameWorld.obstacle1.getX() - GameRenderer.generator2.getValue2(),
                GameWorld.obstacle1.getY() + GameRenderer.generator2.getValue1() , 5, 5);

@Override
public void update(float delta) {

        if (Intersector.overlaps(GameWorld.wizard.getBoundingRectangle(), doublepoints)) {                
            Gdx.app.exit();             
        }    
}

I don't understand why the latter works, but I'd really like to do it with the ArrayList. Can someone tell me why?

Breakpoint (ArrayList):

enter image description here

Breakpoint (normal):

enter image description here


Solution

  • Not sure about the rest of your code but wouldnt below code add a rectangle in each render update? (60 a second)

    public void update(float delta) {
    
    items.add(new Rectangle(GameWorld.obstacle1.getX() - GameRenderer.generator2.getValue2(),
                GameWorld.obstacle1.getY() + GameRenderer.generator2.getValue1() , 5, 5));}
    

    Problem might be related to this issue.

    Use:

    System.out.println(items.size());
    

    to check for it.