0
votes

im making a tile based pygame platformer game

this is my collision checking code:

        # check for collision

        for tile in world.tile_list:
            # check for collision in x direction
            if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height):
                dx = 0
            # check for collision in y direction
            if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
                # check if below the ground i.e. jumping
                if self.vel_y < 0:
                    dy = tile[1].bottom - self.rect.top
                    self.vel_y = 0
                # check if above the ground i.e. falling
                elif self.vel_y >= 0:
                    dy = tile[1].top - self.rect.bottom
                    self.vel_y = 0

when I ran the game I came across a weird bug where the player can move outside of the platform tiles, when the player is supposed to fall down when out of the platform tiles

like this:

1 = tile
0 = player


          0  
111111111


its like there are invisible tiles to the sides of the platform tiles. not sure why this occurs

1

1 Answers

0
votes

The position of the player has 2 components , dx and dy. The current position of the player is (self.rect.x + dx, self.rect.y + dy). This is the positon you have to usse for both collision tests:

for tile in world.tile_list:
            
    # check for collision in x direction
    if tile[1].colliderect(self.rect.x + dx, self.rect.y + dy, self.width, self.height):
        # [...]
            
    # check for collision in y direction
    if tile[1].colliderect(self.rect.x + dx, self.rect.y + dy, self.width, self.height):
        # [...]