jaden.joeyak
jaden.joeyak

Reputation: 101

How do I check for collision correctly?

I'm trying to make a Tile based game and I'm making the walls right now and it's not properly working

I have tried the pygame.sprite.spritecollideany(self, self.game.walls), but that trapped the player inside.

Game:

def run(self):
    # game loop - set self.playing = False to end the game
    self.playing = True
    while self.playing:
        self.dt = self.clock.tick(FPS) / 1000
        self.events()
        self.update()
        self.draw()
        self.player.move()

Player:

def collideWithWalls(self, dx=0, dy=0):

    if pg.sprite.spritecollideany(self, self.game.walls):
        return True

def move(self, dx=0, dy=0):
    if not self.collideWithWalls(dx, dy):
        self.x += dx * TileSize
        self.y += dy * TileSize

I just expected it to stop me from going in it, but it made me go in it but no getting out.

Upvotes: 2

Views: 82

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

It is not sufficient to determine if the current position of the player collides with a wall. You've to check if the new position of the player is on a wall. If a collision is determined, then the movement has to be discarded:

def move(self, dx=0, dy=0):

    # store current position
    x, y = self.rect.x, self.rect.y

    # move player
    self.rect.x += dx * TileSize
    self.rect.y += dy * TileSize

    # determine collision
    if pg.sprite.spritecollideany(self, self.game.walls):

        # discard movement
        self.rect.x, self.rect.y = x, y

Upvotes: 3

Related Questions