Omar
Omar

Reputation: 39

How to stop the sprite's movement when it touches the edges of the screen with Pygame?

I created my first sprite with Pygame and managed to make it move with keyboard keys. However, when it encounters the edges of the screen, it keeps moving beyond them, disappearing from the screen. I would like to make it stop when it touches the edges, how can I do it?

This is my code: https://i.sstatic.net/1jPyQ.jpg

Upvotes: 0

Views: 229

Answers (1)

Mercury Platinum
Mercury Platinum

Reputation: 1569

Heres an example of making the walls solid with an SWIDTH (Screen width) variable, and pygame.math.Vector2.

    if self.rect.right >= SWIDTH:
        self.rect.right = SWIDTH
        self.vel.x = 0
        self.anim_type = 0
        self.accelerating = False

        self.pos.x = self.rect.left

    elif self.rect.left <= 0:
         self.rect.left = 1
         self.vel.x = 0
         self.anim_type = 0
         self.accelerating = False

        self.pos.x = self.rect.left

Upvotes: 2

Related Questions