Getting collisions to work

I am making a game, and so far all has been going well, but when I tried to check if the player collides with a wall, things get weird. The program is supposed to check which way the player is moving and then see if it collided with a wall in that direction, and if so, stop the player from moving that way. It recognizes that the player is traveling in a certain direction, and that it is colliding with a wall in that direction, but it isn’t stopping the player from moving in that direction.
the functions I’m having trouble with are `update_movement`, `move_self`, and `check_collisions` in `game_engine.scripts.cust.player`
Here is a link to the repl
https://replit.com/@tankerguy1917/gaem#game_engine/scripts/cust/player.py

There are better ways to implement collisions, but your current problem is caused by the structure of the `if` statements in `update_movement`.
(Note: please use `not x` instead of `x == False`)

Suppose the player holds key `a` down. They will hit a wall on their left.

``````if self.keys[pygame.K_a]:
if self.collided["left"] == False:
self.movement["left"] = True
self.cur_anim = "left_walk"
else:
self.movement["left"] = False
``````

Notice that `self.movement["left"]` is still `True` from previous updates. It will only become `False` solely on user input, you can see that collisions will never set it to `False` (so player keeps moving despite collision).

The fix here is to combine the nested `if` statement so that it too will use the `else` clause.

``````if self.keys[pygame.K_a] and not self.collided["left"]:
self.movement["left"] = True
self.cur_anim = "left_walk"
else:
self.movement["left"] = False
``````

(Your implementation of movement and collision is a bit complex and contains many redundant things, it’s easy to mess something up.)

2 Likes

Thanks. That didn’t fix everything, but I think I’ve got it from here

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.