# How can I implement rectangle collision response?

I am working on a game in JavaScript and my current implementation of collision uses the shortest distance to push the intersecting object away, which isn't always correct. I've made this diagram of the ideal collision. The red box represents the starting position, the green box represents the proper position and the black box represents the static object it is colliding against. The blue arrow is the velocity vector. With my current implementation, the object would be placed in its final position and pushed out (and in this case it would be pushed left)

How can I fix this?

You can procedurally find out how to do a moving AABB/AABB trace with the formulas on this page.

http://www.realtimerendering.com/intersections.html

Basically those equations will tell you what percentage of your move you should do that frame, which will allow you to place your square at the correct location.

• This looks very promising. That table looks very handy for the future. Thanks!
– Gray
Nov 11 '10 at 5:14

There are a few ways to do this, but one easy way is a binary search over the timeline between last frame and the current one. Say that last frame is at time t, and this frame is at t+1. If a collision happened, back up the objects to t+.5. If a collision is still happening, try t+.25, if not try t+.75. Keep going until the steps are sufficiently small. Then do your test for shortest distance push back. Then make sure to play forward the remaining amount of time (since you backed up to find the collision point.)

The key is to get as close to that point in time as you can, since that will definitively tell you which face collided with which other face.