In this lesson, you’ll add code to keep the player sprite from moving off the screen. After adding the code from the previous lesson, you may notice two small problems:
- The player rectangle can move very fast if a key is held down. You’ll work on that later.
- The player rectangle can move off the screen. Let’s solve that one now.
To keep the player on the screen, you need to add some logic to detect if the rect
is going to move off screen. To do that, you check whether the rect
coordinates have moved beyond the screen’s boundary. If so, then you instruct the program to move it back to the edge:
29# Move the sprite based on user keypresses
30def update(self, pressed_keys):
31 if pressed_keys[K_UP]:
32 self.rect.move_ip(0, -5)
33 if pressed_keys[K_DOWN]:
34 self.rect.move_ip(0, 5)
35 if pressed_keys[K_LEFT]:
36 self.rect.move_ip(-5, 0)
37 if pressed_keys[K_RIGHT]:
38 self.rect.move_ip(5, 0)
39
40 # Keep player on the screen
41 if self.rect.left < 0:
42 self.rect.left = 0
43 if self.rect.right > SCREEN_WIDTH:
44 self.rect.right = SCREEN_WIDTH
45 if self.rect.top <= 0:
46 self.rect.top = 0
47 if self.rect.bottom >= SCREEN_HEIGHT:
48 self.rect.bottom = SCREEN_HEIGHT
KA on May 17, 2020
love these videos.