1
votes

I'm making a tile-based plaformer game with pygame. this is my player sprite:

enter image description here

this is the collision detector code:

 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 run the game as shown in this image: the player can stand outside platforms, enter image description here

I need to get the correct player width so when I use width = player_png.get_width() I get the total width of this image, but I just want the width of the first leg to the second leg so that the collision detector will only consider that width as the player width.

enter image description here

I can manually assign the width to the width from the first leg to the second leg but when I do that the collision detector detects that width to the middle of the image and doesn't align it correctly

1

1 Answers

1
votes

There is no automatic solution to this. You need to define a sub-area for the collision test:

offset_x   = # offset_x is the first distance to the "black" pixel
foot_width = # width of the foots

foot_x = self.rect.x + offset_x 

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
    
    # check if below the ground i.e. jumping
    if self.vel_y < 0:
        if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
            dy = tile[1].bottom - self.rect.top
            self.vel_y = 0

    # check if above the ground i.e. falling
    if self.vel_y >= 0:
        if tile[1].colliderect(foot_x, self.rect.y + dy, foot_width, self.height):
            dy = tile[1].top - self.rect.bottom
            self.vel_y = 0