vendredi 26 décembre 2014

Must collisions be detected "before" or "after" moving the object?

I want to ask this question the most theoretically I can. Forget about programming languages and APIs, please.


Let's suppose that we have a square that we move with the keyboard. In the screen where our square lives, there exists an obstacle too. This obstacle is a rectangle, and it is solid. This means that if, for example, our square hits it from the left side (the left side of the obstacle), the square won't be able to advance in that direction (like a wall).


This is very simple, so now, I think there are two main ways to approach this problem. Let's suppose that we use hit-testing collision for detecting it:


-Make the move (with time-difference between frames), and see if the new move made a collision. If the new move made a collision, "correct" the coordinate that made the hit (it could be x or y).


-See if updating x will make a collision. If it makes it, don't update x (or update it at it's maximum before collisioning the obstacle). Make the same with y.


Actually, I'm using the second method, and it works perfectly! First, I tried the first method, but I saw a big problem with it. When you make a collision after moving, it means that my player got "into" the obstacle. But the collision could have been caused from a lot of possible directions, so how will I know which one is the correct direction in which I have to correct the coordinates? It may be done well, but it's complicating the code when I can simply choose the second way.


I'm doing this in SDL, and the second way works nicely.


What's your opinion?


Aucun commentaire:

Enregistrer un commentaire