Reacting to rectangle on rectangle collisions
- by mcjohnalds45
I don't know how to react to collisions between two axis aligned rectangles that have x, y, width and height values (x and y are from the centre of the box) to make them simply not overlap.
I figured I'd just make them move away from each other depending on how far they intersect in the opposite direction (left, right, up or down) of where they collided. If I check for collisions only on the x axis or only on the y axis it works fine, but when checking for both collisions crazy stuff happens.
This code executes when the first box collides with the second. It's in lua but feel free to answer in anything that isn't to too counter-intuitive.
if box1.x < box2.x then
box1.x = box1.x + box2.x - box1.x - (box1.width / 2) - (box2.width / 2)
end
if box1.x > box2.x then
box1.x = box1.x - (box1.x - box2.x - (box1.width / 2) - (box2.width / 2))
end
if box1.y < box2.y then
box1.y = box1.y + box2.y - box1.y - (box1.height / 2) - (box2.height / 2)
end
if box1.y > box2.y then
box1.y = box1.y - (box1.y - box2.y - (box1.height / 2) - (box2.height / 2))
end