0

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

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
MakeTheErrorDie
  • 87
  • 1
  • 1
  • 10

1 Answers1

0

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):
        # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • when I added self.rect + dx and self.rect + dy, the player sprite can't move forward or backwards – MakeTheErrorDie May 11 '21 at 14:02
  • @MakeTheErrorDie So there are still more bugs in your application. I can't see your complete code, so I can just spot what's obvious. – Rabbid76 May 11 '21 at 14:03
  • ok I found out the bug was caused because my sprite png is a character with a transparent background so the dimensions are 200x140 and because the entire image is not the character then it looks as if the character is floating outside the platform, :/ – MakeTheErrorDie May 11 '21 at 14:15
  • not sure how to fix it because there are protruding parts (e.i. swords) which come to the left of the character so the png has to be in the dimension of 200x140 – MakeTheErrorDie May 11 '21 at 14:16
  • 1
    @MakeTheErrorDie See [How to get the correct dimensions for a pygame rectangle created from an image](https://stackoverflow.com/questions/65361582/how-to-get-the-correct-dimensions-for-a-pygame-rectangle-created-from-an-image/65361896#65361896) – Rabbid76 May 11 '21 at 14:17