Calculate the new position of the player
Check if new position causes a collision
If it does not, then move to the new position
Otherwise, move to the spot closest to the new position, that does not cause collision (touch the wall).
I use a slightly different approach:
- Move the player to a new position
- Find all nearby colliding objects
- If necessary, adjust the player's position so that he's not colliding with those objects
Inny wrote:
- Generalize the collision function to work on a single axis at a time, and perform them separately (i.e. apply the change in X first, then do Y).
- Iterate over all nearby objects with potential collisions. If the Player overlaps a wall, only move them off the wall in the direction they came from, and only in the component direction being tested.
- Then, switch to the other component and reiterate over all of those nearby objects again.
- The Player's final position is the changed X position combined with the changed Y position.
What you get from doing it this way is, lets say it's a platformer. By performing the Y collision first, the player is moved from inside the floor to on top of the floor in the first pass. Then, when you perform the X movement and collision detection, the player is already just above the floor, so the X can move without problem, meaning regular horizontal movement feels more like regular walking/sliding without the feel that you're stopping every 16 pixels.
Could you please explain how resolving the collisions one axis at a time would solve the problem altogether?
I mean yes, if you resolve the Y axis first you won't get stuck during horizontal movement.
BUT in that case, you can get stuck during vertical movement - while falling next to walls for example.