Home  >  Article  >  Backend Development  >  How to Prevent Ball from Crossing Boundaries in PyGame?

How to Prevent Ball from Crossing Boundaries in PyGame?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 21:00:30298browse

How to Prevent Ball from Crossing Boundaries in PyGame?

How to Make a Ball Bounce Off Walls with PyGame

Problem

In PyGame, how do you prevent a ball from going inside a wall when it hits one?

Solution

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>

Example

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn