Rectangle Rectangle Collision Detection

in

So let’s say you have two rectangles on your screen one red and one blue. If they overlap at any point in time, that means there has been a collision between the two! This can be useful for all sorts of things like detecting when objects are colliding with each other or figuring out if a player’s character is touching an obstacle in a game.

Here’s how it works: first, we calculate the position and size of both rectangles (which is pretty easy since they’re just boxes). Then, we check to see if there is any overlap between them by comparing their coordinates and dimensions. If there is overlap, that means there has been a collision!

For example, let’s say our red rectangle has the following properties:
– x position = 100 pixels
– y position = 50 pixels
– width = 200 pixels
– height = 100 pixels

And our blue rectangle has these properties:
– x position = 300 pixels
– y position = 75 pixels
– width = 150 pixels
– height = 100 pixels

To check for a collision, we would first calculate the intersection between the two rectangles. This is done by finding the overlap in both the x and y dimensions:

x_intersection = max(0, min(red_rectangle[x + width], blue_rectangle[x]) max(red_rectangle[x], blue_rectangle[x]))
y_intersection = max(0, min(red_rectangle[y + height], blue_rectangle[y]) max(red_rectangle[y], blue_rectangle[y]))

If either of these values is greater than zero (meaning there is overlap), then we have a collision! In this case, the x and y intersection would be calculated as follows:

x_intersection = max(0, min(red_rectangle[x + width], blue_rectangle[x]) max(red_rectangle[x], blue_rectangle[x]))
= max(0, min(300+200, 500) max(100, 300))
= max(0, 700-400)
= 300

y_intersection = max(0, min(red_rectangle[y + height], blue_rectangle[y]) max(red_rectangle[y], blue_rectangle[y]))
= max(0, min(150+100, 650) max(50, 75))
= max(0, 750-250)
= 500

So in this case, there is a collision between the two rectangles! This can be useful for all sorts of things like detecting when objects are colliding with each other or figuring out if a player’s character is touching an obstacle in a game.

SICORPS