0

I have created a maze game where the user controls a ball and has to move it through a maze. The issue I'm running into is when the ball collides with a wall, it should not go through the wall. I have been able to detect collision by using this: https://stackoverflow.com/a/402010/11365940

I am unsure how to prevent the ball from going past the wall.

I have tried doing things such as

BALL_X = wall.left - BALL_RADIUS;

which will work only when the right of the ball has hit the left of the wall. But I do not know how to detect that. I only know how to detect a collision.

Here is some code that I have written to detect collisions.

for (Rect wall : walls) {
    double wallWidth = wall.right - wall.left;
    double wallHeight = wall.bottom - wall.top;
    double wallX = wallWidth / 2 + wall.left;
    double wallY = wallHeight / 2 + wall.top;
    double circleDistanceX = Math.abs(BALL_X - wallX);
    double circleDistanceY = Math.abs(BALL_Y - wallY);
    if (circleDistanceX > wallWidth / 2 + BALL_RADIUS) {
        continue;
    }
    if (circleDistanceY > wallHeight / 2 + BALL_RADIUS) {
        continue;
    }
    if (circleDistanceX <= wallWidth / 2) {
        // collision here
    }
    if (circleDistanceY <= wallHeight / 2) {
        // collision here
    }
    double cornerDistanceSq = Math.pow(circleDistanceX - wallWidth, 2) +
            Math.pow(circleDistanceY - wallHeight, 2);
    if (cornerDistanceSq <= BALL_RADIUS) {
        // collision here
    }
}

1 Answers1

0

So you have to always detect whether they are overlapping each other, here is the code

if(Math.abs(circle.CircleCenterY - rectangle.top) < circle.radius) {
    if(circle.CircleCenterX >= rectangle.left) {
         if(circle.CircleCenterY <= rectangle.right) {
             // circle touched the top edge
         }
         else {
             // circle touched the right corner
         }
    }
    else {
         // circle touched the top left corner
    }
}
Mahabub Karim
  • 810
  • 11
  • 17