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
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);
}