0
votes

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.

1
Is the game completely based on cells? As in every single object would be in a certain cell and the player can never be in a cell that an obstacle is in? - Sanil Khurana
This is dynamic game, so, cell size is 64px, and player speed can be different, like (5, 5) etc. Cells is only location characteristc, player can walk where he wants. Hmm, like Minecraft. It has blocks, but player can move not only between blocks - Adam Arutyunov
Have you written any code? Seeing code would be helpful since this is a very broad question. - Sanil Khurana
Sorry, I deleted code that process the collision. But i have this: GameObject class, Wall class(GameObject), Player class(GameObject), and every tick I can put anything in player.update() function. - Adam Arutyunov

1 Answers

0
votes

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?