1

After implementing collisions in my pygame player class, when the player collides with a wall, and the user is holding that corresponding key along with any key that makes the player move in a different axis then the play will "slingshot" across the screen. I believe this has something to do with the tile maps glitching the player off the screen but I'm not 100% certain.

The collision code is...

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

where tile is derived from a function above that maps the tiles to the screen and the self.rect and speed are properties of the player from the above player class.

A video example of the issue... https://www.youtube.com/watch?v=FbJAC3LulHM&ab_channel=spretzelz

Full Code... https://pastebin.pl/view/9dc1c4aa

  • 1
    in some examples you can see that first you move one direction - ie. left-right - and check collisions - and later you move other direction - top-botton - and check collision again. See `update()` in [move_with_walls_example.py](http://programarcadegames.com/python_examples/show_file.php?file=move_with_walls_example.py) – furas Jun 02 '21 at 01:07
  • you could keep tiles on list and then you would blit them without all these `if/else` – furas Jun 02 '21 at 01:10
  • shorter `for y, row in enumerate(game_map):` and then you don't need `y = 0` and `y += 1` – furas Jun 02 '21 at 01:12
  • there is good rule: `CamelCaseNames` for classes - `class Player` - similar to other classes like `class Sprite`, `class Rect`. It helps to recognize class in code. More: [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) – furas Jun 02 '21 at 01:13
  • @furas I viewed and implemented the code from that .py file and that method doesn't work for me. I'm getting an error saying AttributeError: 'pygame.Rect' object has no attribute 'rect'. –  Jun 02 '21 at 22:50
  • you have to create class with `self.rect = pygame.Rect(...)` inside this class but it seems you created directly `pygame.Rect(...)` – furas Jun 02 '21 at 22:55
  • 1
    BTW: if you have problem with your code then use `print()` to see values in variables in different moments and which part of code is executed - it is called `"print debuging"`. It helps to see what program is doing and when it has problem - and what values makes problem. – furas Jun 02 '21 at 22:56

0 Answers0