As far as I can see your horizontal movement and collision detection work correctly. I enabled the vertical movement again and had to fix only a few things. Wall
had to be changed to hits[0]
and the y-velocity had to be set to 0
after touching a wall.
def collide_with_walls(self, dir):
if dir == 'x':
hits = pg.sprite.spritecollide(self, self.game.walls, False)
if hits:
if self.pos.x > 0:
self.pos.x = hits[0].rect.left - self.rect.width
if self.pos.x < 0:
self.pos.x = hits[0].rect.right
self.rect.x = self.pos.x
if dir == 'y':
hits = pg.sprite.spritecollide(self, self.game.walls, False)
if hits:
if self.pos.y >= 0:
# `Wall` had to be changed to `hits[0]`.
self.pos.y = hits[0].rect.top - self.rect.height
if self.pos.y < 0:
self.pos.y = hits[0].rect.bottom
self.rect.y = self.pos.y
self.vel.y = 0 # Stop the player, otherwise he'll keep accelerating.
There’s still a problem: If the player sprite falls too long, it will accelerate and move so fast downwards that it can skip the collision detection with the wall and will just fall through it. Make sure that the sprite can’t skip the collision detection, either by limiting the distances that it can fall, giving it a maximum speed or simply by making the walls thicker. You could also use ray casting, but that would be a bit more complex to implement.
1
solved Collision detection on the y-axis does not work (pygame)