I am trying to figure out how to determine the direction a collision occurs between two rectangles.
One rectangle does not move. The other rectangle has a velocity in any direction. When a collision occurs, I want to be able to set the position of the moving rectangle to the point of impact.
I seem to be stuck in determining from what direction the impact occurs. If I am moving strictly vertically or horizontally I manage great detection. But when moving in both directions at the same time, strange things happen.
What is the best way to determine what direction a collision occurs between two rectangles?
Answer
I seem to be stuck in determining from what direction the impact occurs. If I am moving strictly vertically or horizontally I manage great detection. But when moving in both directions at the same time, strange things happen.
tl;dr The solution is to move and check for collisions one axis at a time.
I had this very same problem. I bet that the update phase of your game loop looks something like this:
- object.x += object.vx
- object.y += object.vy
- check for collisions
- repsond to collisions
The trick here is to move and check for collisions one axis at a time. As you said, "If I am moving strictly vertically or horizontally I manage great detection." So you've already solved 99% of the problem. Just change your logic to look like this:
- object.x += object.vx
- check/respond collisions
- object.y += object.vy
- check/respond collisions
In simple cases, it doesn't matter which axis you do first. If you don't feel good about choosing one or the other arbitrarily, it's reasonable to check first the axis where the object's absolute velocity is the greatest.
No comments:
Post a Comment