Skip to content Skip to sidebar Skip to footer

Collision Detection On The Y-axis Does Not Work (pygame)

I am trying to get the collision detection in my code to work. I am using vectors and I want the player sprite to collide and stop when it collides with a sprite group called walls

Solution 1:

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.

defcollide_with_walls(self, dir):
    ifdir == '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
    ifdir == '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.

Post a Comment for "Collision Detection On The Y-axis Does Not Work (pygame)"