Reacting to rectangle on rectangle collisions

Posted by mcjohnalds45 on Game Development See other posts from Game Development or by mcjohnalds45
Published on 2012-09-08T08:43:30Z Indexed on 2012/09/08 9:51 UTC
Read the original article Hit count: 299

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

© Game Development or respective owner

Related posts about collision-detection

Related posts about rectangle