I want my character in pygame to not go off the screen

Viewed 88

I am trying to make a simple platformer in pygame where the player will return to the begging of the window if they go to far to the right. However, my code is not working and the player is able to go off the screen and does not return to the start. This is my code so far:

class Player(pg.sprite.Sprite):

    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((30,40))
        self.image.fill(green)
        self.rect = self.image.get_rect()
        self.rect.center = (width /2, height /2)
        self.speed_x = 0
        self.speed_y = 0
        self.pos = 480

    def update(self):
        self.speed_x = 0
        player_input = pg.key.get_pressed()
        if player_input[pg.K_LEFT]:
            self.speed_x = -5

        if player_input[pg.K_RIGHT]:
            self.speed_x = 5

        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        # wrap around the sides of the screen
        if self.pos > 480:
            self.pos  = 0
        if self.pos < 0:
            self.pos = -480,0
2 Answers

You have to change self.rect.x and self.rect.y rather than self.pos

The easiest way to achieve what you want is to use the % (modulo) operator. The % (modulo) operator yields the remainder from the division of the first argument by the second. See Binary arithmetic operations.

For instance:

class Player(pg.sprite.Sprite):
    # [...]

    def update(self):

        # [...]

        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        rect.centerx = rect.centerx % width
        rect.centery = rect.centery % height

when you move the player, you change self.rect.x, but not change self.pos, so when you move off the screen, self.pos will still = 480, so you want to check if self.rect.x is off the screen, then reset that.

# wrap around the sides of the screen
if self.rect.x > 480:
    self.rect.x  = 0
if self.rect.x < 0:
    self.rect.x = 480
Related