How do you get pygame to give warning when player touches side of screen?
Solution 1:
Define a pygame.Rect
object for the player:
player_rect = pygame.Rect(w, y, width, height)
or get a rectangle from the player image (player_image
):
player_rect = player_image.get_Rect(topleft = (x, y))
Get the rectangle of the display Surface (screen
)
screen_rect = screen.get_rect()
Evaluate if the player is out of the screen:
if player_rect.left < screen_rect.left or player_rect.right < screen_rect.right or \
player_rect.top < screen_rect.top or player_rect.bottom < screen_rect.bottom:
printe("You can't touch the screen sides")
See pygame.Rect.clamp()
respectively pygame.Rect.clamp_ip()
:
Returns a new rectangle that is moved to be completely inside the argument Rect.
With this function, an object can be kept completely in the window:
player_rect.clamp_ip(screen_rect)
You can use the clamped rectangle to evaluate whether the player is touching the edge of the window:
screen_rect = screen.get_rect()
player_rect = player_image.get_Rect(topleft = (x, y))
clamped_rect = player_rect.clamp(screen_rect)
if clamped_rect.x != player_rect.x or clamped_rect.y != player_rect.y:
printe("You can't touch the screen sides")
player_rect = clamped_rect
x, y = player_rect.topleft