Search code examples
javaandroidcollision-detection

Point and Rectangle collision detection?


So I have created a method that detects collision between a BallView ball and a Rectangle rect. I have broken it up into 4 parts; it detects collision between the very top of the circle, very left of the circle, very bottom of the circle, and the very right of the circle, and the rectangle. Two of those work which are detecting a collision between the left point on the circle and a rectangle and detecting a collision between a the right point on the circle and the rectangle. But, what won't work is if the very top point or the very bottom point touch the rectangle no collision is detected as I can see when I log the if statement to see if it is entered. Here is my code (the method .getR() gets the circles radius):

public boolean intersects(BallView ball, Rectangle rect){
    boolean intersects = false;

    //Left point
    if (ball.getX() - ball.getR() >= rect.getTheLeft() &&
        ball.getX() - ball.getR()<= rect.getTheRight() &&
        ball.getY() <= rect.getTheBottom() &&
        ball.getY() >= rect.getTheTop())
    {
        intersects = true;
    }

    //Right point
    if (ball.getX() + ball.getR() >= rect.getTheLeft() &&
        ball.getX() + ball.getR() <= rect.getTheRight() &&
        ball.getY() <= rect.getTheBottom() &&
        ball.getY() >= rect.getTheTop())
    {
        intersects = true;
    }

    //Bottom point (wont work?)
    if (ball.getX() >= rect.getTheLeft() &&
        ball.getX() <= rect.getTheRight() &&
        ball.getY() + ball.getR() <= rect.getTheBottom() &&
        ball.getY() + ball.getR()>= rect.getTheTop())
    {
        intersects = true;
    }

    //Top point (wont work?)
    if (ball.getX() >= rect.getTheLeft() &&
        ball.getX() <= rect.getTheRight() &&
        ball.getY() - ball.getR()<= rect.getTheBottom() &&
        ball.getY() - ball.getR()>= rect.getTheTop())
    {
        intersects = true;
    }

    return intersects;

}

I have taken into account that Y increases as you go down and X increases as you go right. Why won't this method detect intersection for the top and bottom points on the circle's edge? Also, the screen is oriented landscape.


Solution

  • It looks like it's just a logic error, I'm assuming .getX and .getY are the x and y coordinates of the center of the ball, as well as .getR being the radius, so you'd want your code to look something like this

    if (ball.getX() + ball.getR() >= rect.getTheLeft() &&
        ball.getX() - ball.getR() <= rect.getTheRight() &&
        ball.getY() - ball.getR() <= rect.getTheBottom() &&
        ball.getY() + ball.getR() >= rect.getTheTop())
    {
        intersects = true;
    }
    

    I'm not sure about the specifics of your app, but I'm not sure you even need more than that to tell if the ball is intersecting the rectangle