I made a border in this pong game, but the paddles can cross it. How do I stop that?
Solution 1:
PyGame has a feature that does exactly what you want it to do. Use pygame.Rect
objects and 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. Get the window rectangle with get_rect
and clamp the object in the window:
while run:
# [...]
key = pygame.key.get_pressed()
if key[pygame.K_w]:
paddle1.rect.y += -paddle_speed
# [...]
winRect = win.get_rect()
paddle1.rect.clamp_ip(winRect)
paddle2.rect.clamp_ip(winRect)
paddle3.rect.clamp_ip(winRect)
paddle4.rect.clamp_ip(winRect)
# [...]