Home > OS >  How to check if a player has collided with any wall Java
How to check if a player has collided with any wall Java

Time:04-10

I am making a maze game and I am trying to implement a wall feature that will restrict the movement of a player if he collides with a wall. I have created a wall class so that I can implement multiple walls manually. The problem is my intersectsWith method which detects if a circle and a rectangle are colliding(player is a circle) takes in a player of type Player and a single wall of type Wall. How would I make it so that my method can detect collision to all the walls in the game and not just one so that if my player encounters any wall it would detect it? I feel like I need to use an ArrayList of walls or something like that. Here is the code for my collision detection which is in the player class:

public boolean intersectsWith(Wall wall) {
        double testX = x;
        double testY = y;

        if (x < wall.getX()) {
            testX = wall.getX();
        } else if (x > wall.getX()   wall.getWidth()) {
            testX = wall.getX()   wall.getWidth();
        }

        if (y < wall.getY()) {
            testY = wall.getY();

        } else if (y > wall.getY()   wall.getHeight()) {
            testY = wall.getY()   wall.getHeight();
        }

        double distanceX = x - testX;
        double distanceY = y - testY;

        double distance = Math.sqrt(distanceX * distanceX   distanceY * distanceY);

        if (distance < radius) {
            return true;
        } else {
            return false;
        }
    }

CodePudding user response:

I actually just made a game engine, so I've worked with collisions quite a bit.


  • First of all, you are correct, add all your walls to an ArrayList and loop through them and check if the player's rectangle collides with the other rectangle. Something like this (pseudocode):
for (Wall w : wallsArrayList) {
   if (myRectangle.intersects(w)) {
      return true;
   }
}
  • If performance is an issue, you could try this, however I have not run into any issues in my games using the solution above:
  • Create a Rectangle object that follows the player around, you could make it the size of the viewport if you want, or just make it a bit larger than the player. Get all the Rectangles inside the larger rectangle that follows the player, then loop through those and check the collisions. As far as performance goes, I'm not entirely sure if it's too much better, but in my mind, it seems like it would be.

    this is my first answer on Stackoverflow... so lemme know if I did anything wrong :)
  • Related