A.J.
A.J.

Reputation: 89

how can I get my character to stop going past the right side of the screen?

I made a sprite that is 30x30 pixels. It keeps going over the right side of the screen, and i know it has something to do with the velocity

i've tried subtracting player.vel from w as well and it didnt work.

h = 550
w = 360
win = pygame.display.set_mode((w,h))

here are my conditional statements:

 if key[pygame.K_a] and player.x > 0:
     player.x -= player.vel
 if key[pygame.K_d] and player.x < w - 30:
     player.x += player.vel     

player.vel is equal to 20

I need my sprite to stop going over the screen or stopping way before the end of the screen. Thank you

Upvotes: 1

Views: 72

Answers (1)

Kingsley
Kingsley

Reputation: 14906

The sprite is drawn from the top-left corner, so that means the sprite can be drawn completely from sprite.rect.x >= 0 and sprite.rect.x < WINDOW_WIDTH - sprite.rect.width. (And similarly for y).

This gives you two approaches:

  1. Before moving, calculate how much of player.vel can be used, and limit it.
  2. After moving, ensure the player x,y is still on-screen.

Usually I find the second option to be easier:

class PlayerSprite( pygame.sprite.Sprite ):
    def __init__( self, bitmap, x, y ):
        pygame.sprite.Sprite.__init__( self )
        self.image = bitmap
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

    def move( self, x_dir, y_dir ):
        self.rect.x += x_dir
        self.rect.y += y_dir
        # stay on screen
        if ( self.rect.x < 0 ):
            self.rect.x = 0
        elif ( self.rect.x > WINDOW_WIDTH - self.rect.width ):
            self.rect.x = WINDOW_WIDTH - self.rect.width - 1
        if ( self.rect.y < = 0 ):
            self.rect.y = 0
        elif ( self.rect.y > WINDOW_HEIGHT - self.rect.height ):
            self.rect.y = WINDOW_HEIGHT - self.rect.height - 1

    def update( self ):
        pass # TODO

Which means the calling code need not worry about vel, or the position:

if key[pygame.K_a]:
    player.move( -player.vel, 0 )  # left
if key[pygame.K_d]:
    player.move( player.vel, 0 )   # right
if key[pygame.K_w]:
    player.move( 0, -player.vel )  # up
if key[pygame.K_x]:
    player.move( 0, player.vel )   # waaay down

Upvotes: 1

Related Questions