In my pygame dungeon rpg when my player collides with a wall at the top or the bottom of its rect and I move the player in either x-direction, the player gets slingshotted off the screen. Using print debugging I've realized that when the player is colliding with the top it hits the individual hitboxes of the tiles and slingshots it to the outside of my game map because of how my collisions work.

    def colliders(self):
        hit_list = self.collision_test(tile_rects)
        for tile in hit_list:
            if self.speed[0] > 0:
                self.rect.right = tile.left
            elif self.speed[0] < 0:
                self.rect.left = tile.right
        hit_list = self.collision_test(tile_rects)
        for tile in hit_list:
            if self.speed[1] > 0:
                self.rect.bottom = tile.top
            elif self.speed[1] < 0:
                self.rect.top = tile.bottom

The tile is derived from the hitboxes of each individual tile in the above function. Speed and rect are derived from my player init function above.

Video of error: https://www.youtube.com/watch?v=FbJAC3LulHM&feature=youtu.be&ab_channel=spretzelz

Code: https://pastebin.com/jXav1PdU

  • \$\begingroup\$ Please provide all the relevant code about how you resolve the collision inside the post, without relying on an external link. \$\endgroup\$ – Vaillancourt Jun 3 at 0:42

When a character collides with a tile while moving up, the collision must push back on the Y axis first, but your code unconditionally checks X axis first.

Choose an axis based on the penetration direction, like this:

    if abs(self.rect.centerx - tile.rect.centerx) > abs(self.rect.centery - tile.rect.centery):
        # resolve X axis
        # resolve Y axis

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.