I'm making a game with Pygame, and now I stuck on how to process collision between player and wall. This is 2D RPG with cells, where some of them are walls. You look on world from top, like in Pacman.
So, I know that i can get list of collisions by pygame.spritecollide() and it will return me list of objects that player collides. I can get "collide rectangle" by player.rect.clip(wall.rect), but how I can get player back from the wall?
So, I had many ideas. The first was push player back in opposite direction, but if player goes, as example, both right and bottom directions and collide with vertical wall right of itself, player stucks, because it is needed to push only left, but not up.
The second idea was implement diagonally moving like one left and one bottom. But in this way we don't now, how move first: left or bottom, and order becomes the most important factor.
So, I don't know what algorithm I should use.
If you know the location of the centre of the cell and the location of the player you can calculate the x distance and the y distance from the wall at that point in time. Would it be possible at that point to take the absolute value of each distance and then take the largest value as the direction to push the player in.
e.g. The player collides with the right of the wall so the distance from the centre of the wall in the y direction should be less than the distance in x.
Therefore you know that the player collided with the left or the right of the wall and not the top, this means the push should be to the right or the left.
If the player's movement is stored as in the form [x, y] then knowing whether to push left or right isn't important since flipping the direction of movement in the x axis gives the correct result.
The push should therefore be in the x direction in this example
e.g. player.vel_x = -player.vel_x.
This would leave the movement in the y axis unchanged so hopefully wouldn't result in the problem you mentioned.
Does that help?
Walls logic in Pygame