Page 1 of 1
Get the dimensions of the overlapping section of two rectangles
Posted: Wed May 24, 2023 5:15 pm
by baconhawka7x
I'm trying to get the width and height of the overlapping section of two rectangles (assuming the rectangles can't rotate).
For example, if there is a player and a platform, I can check
if they are overlapping.
Code: Select all
if player.x + player.width > platform.x and
player.x < platform.x + platform.width and
player.y + player.height > platform.y and
player.y < platform.y + platform.height then
-- Player and platform are overlapping
end
But my goal is to get the width and height of the resulting intersecting rectangle, and use that to properly resolve the collision.
For some reason I'm having a hard time trying to make sure I explain this properly, if its unclear please let me know
Re: Get the dimensions of the overlapping section of two rectangles
Posted: Wed May 24, 2023 6:48 pm
by Andlac028
If you are sure, the rectangles overlap, you can find it this way. Imagine some situation:
Code: Select all
+--------------+
| |
| +--------+ |
| | | |
| | | |
+--|--------|--+
| |
+--------+
Now we can see, that if we want to get x of overlap, it is math.max(x1, x2) where x1 and x2 are x positions of two rectangles. Same applies to y. If we want to get x + w of overlap, it is math.min(x1 + width1, x2 + width2). Same applies to y. (basically, the left point of intersect is the rightmost left point, the right point is the leftmost of the right point, the top point is the lowest of top points and the lower point is the highest of lowest points).
Re: Get the dimensions of the overlapping section of two rectangles
Posted: Wed May 24, 2023 7:36 pm
by baconhawka7x
Andlac028 wrote: ↑Wed May 24, 2023 6:48 pm
If you are sure, the rectangles overlap, you can find it this way. Imagine some situation:
Code: Select all
+--------------+
| |
| +--------+ |
| | | |
| | | |
+--|--------|--+
| |
+--------+
Now we can see, that if we want to get x of overlap, it is math.max(x1, x2) where x1 and x2 are x positions of two rectangles. Same applies to y. If we want to get x + w of overlap, it is math.min(x1 + width1, x2 + width2). Same applies to y. (basically, the left point of intersect is the rightmost left point, the right point is the leftmost of the right point, the top point is the lowest of top points and the lower point is the highest of lowest points).
This is exactly what I was trying to solve thank you so much!
For anyone interested here's a simple little function for it
Code: Select all
function getIntersectingRectangle(rect1, rect2)
local intersect = {
x = math.max(rect1.x,rect2.x),
y = math.max(rect1.y,rect2.y),
}
intersect.width = math.min(rect1.x + rect1.width, rect2.x + rect2.width) - intersect.x
intersect.height = math.min(rect1.y + rect1.height, rect2.y + rect2.height) - intersect.y
return intersect
end