In PyGame, how do you prevent a ball from going inside a wall when it hits one?
Nested Loops:
The issue arises from using multiple nested loops. It's more efficient to handle movement within the application loop.
<code class="python">while run: # Handle movement continuously box.y -= box.vel_y box.x += box.vel_x</code>
Boundary Definition:
Define a rectangular region for ball movement using a pygame.Rect object:
<code class="python">bounds = window.get_rect() # full screen bounds = pygame.Rect(450, 200, 300, 200) # rectangular region</code>
Boundary Collision Handling:
Update ball direction when it intersects with the boundaries:
<code class="python">if box.x - box.radius < bounds.left or box.x + box.radius > bounds.right: box.vel_x *= -1 if box.y - box.radius < bounds.top or box.y + box.radius > bounds.bottom: box.vel_y *= -1</code>
<code class="python">box = Circle(600,300,10) run = True start = False clock = pygame.time.Clock() while run: clock.tick(120) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: start = True bounds = pygame.Rect(450, 200, 300, 200) if start: box.y -= box.vel_y box.x += box.vel_x if box.x - box.radius < bounds.left or box.x + box.radius > bounds.right: box.vel_x *= -1 if box.y - box.radius < bounds.top or box.y + box.radius > bounds.bottom: box.vel_y *= -1 window.fill((0,0,0)) pygame.draw.rect(window, (255, 0, 0), bounds, 1) pygame.draw.circle(window, (44,176,55), (box.x, box.y), box.radius) pygame.display.update()</code>
The above is the detailed content of How to Prevent Ball from Crossing Boundaries in PyGame?. For more information, please follow other related articles on the PHP Chinese website!