Collision detection between two rectangles in java

前端 未结 5 2068
粉色の甜心
粉色の甜心 2020-12-10 17:59

I have two rectangles, the red rectangle (can move) and the blue rectangle. Both have: x, y, width, height.

How can I say in a programming language such as Java when

5条回答
  •  旧巷少年郎
    2020-12-10 18:31

    You have to check both the intersection along the x-axis and along the y-axis. If any of them is missing, there is no collision between rectangles.

    Code for 1-D:

    boolean overlaps(double point1, double length1, double point2, double length2)
    {
        double highestStartPoint = Math.max(point1, point2);
        double lowestEndPoint = Math.min(point1 + length1, point2 + length2);
    
        return highestStartPoint < lowestEndPoint;
    }
    

    You have to call it for both x and y:

    boolean collision(double x1, double x2, double y1, double y2, double width1, double width2, double height1, double height2)
    {
        return overlaps(x1, width1, x2, width2) && overlaps (y1, height1, y2, height2);
    }
    

提交回复
热议问题