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
. The problem is that the player can pass through the bottom wall.
I've turned the gravity off in this example.
The x collision is okay but it draws a bit funny, only the y direction won't work properly with the same code.
I've already tried to debug the code with a debugger to no avail.
I'm mainly interested in figuring out why the vertical collision detection doesn't work, but I'd also appreciate suggestions about the horizontal collision detection.
LINKS: Github : Complete code
Current collision detection code:
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:
self.pos.y = Wall.rect.top - self.rect.height / 2
if self.pos.y < 0:
self.pos.y = hits[0].rect.bottom
self.rect.y = self.pos.y