Search code examples
javacollision-detectionrectangles

collision with rectangle.intersects [Java]


So, I'm trying to make a collision for the walls in my game using Rectangles, and I decided to try and use an ArrayList to store the rectangles of each wall, and I make the entire field a wall, and all I want to do is remove three of the walls, so I'm doing shapeList.remove(0) to try and remove the first wall at 0,0 but its not working, I don't know if i'm doing it wrong, or if theres a better way, but I could use some help solving this issue, here is the code.

    public void walls(Graphics g) {
    for (int i = 0; i < 63; i++) {
        for (int wallsX = 0; wallsX < 750; wallsX += 95) {
            for (int wallsY = 0; wallsY < 750; wallsY += 95) {
                shapeList.add(new Rectangle(wallsX, wallsY, 95, 95));
                g.setColor(Color.blue);
                g.drawRect(wallsX, wallsY, 95, 95);
            }
        }
    }
    shapeList.remove(0); //I want to remove wall at 0,0... but not working
    g.setColor(Color.black);
    g.fillRect(0, 0, 95, 95);
    g.fillRect(95, 0, 95, 95);
    g.fillRect(0, 95, 95, 95);

    for (int i = 0; i < shapeList.size(); i++) {
        if (intersectsBox(getRectangle(), shapeList.get(i))) {
            isInsideWalls = true;

        }else{
            isInsideWalls = false;
        }
    }
}

EDIT: When i run this code, this error appears:

`Exception in thread "AWT-EventQueue-0" Exception in thread "Timer-0" java.lang.NullPointerException
    at java.awt.Rectangle.intersects(Unknown Source)
    at bombermangame.Game.intersectsBox(Game.java:122)
    at bombermangame.Game.walls(Game.java:147)
    at bombermangame.Game.paintComponent(Game.java:161)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)

Solution

  • The following loop below will need to be removed as it creates 63 copies of your wall grid. What this means is that every single coordinate you specify will contains 63 rectangles.

     for (int i = 0; i < 63; i++) {
    

    The reason removing the for loop will fix at least one of your problems is because when you remove the first rectangle, there are 62 rectangles left at the same coordinate.

    All you will need to create your list of walls is the following:

    for (int wallsX = 0; wallsX < 750; wallsX += 95) {
          for (int wallsY = 0; wallsY < 750; wallsY += 95) {
               shapeList.add(new Rectangle(wallsX, wallsY, 95, 95));
               g.setColor(Color.blue);
               g.drawRect(wallsX, wallsY, 95, 95);
          }
    }
    

    Now once you apply shapeList.remove(0);

    There should be no walls at coordinate (0,0) anymore.

    There may be other errors in your code that I am unaware of though. I've only looked at your code that you've provided in your question.