How to make ball bounce off wall with Pygame?

前端 未结 2 1503
暖寄归人
暖寄归人 2020-12-07 04:42

Before you criticize me for not googling or do research before asking, I did research beforehand but to no avail.

I am trying to create the Atari Br

相关标签:
2条回答
  • 2020-12-07 05:26

    The issue are the multiple nested loops. You have an application loop, so use it.
    Continuously move the ball in the loop:

    box.y -= box.vel_y        
    box.x += box.vel_x
    

    Define a rectangular region for the ball by a pygame.Rect object:

    bounds = window.get_rect() # full screen
    

    or

    bounds = pygame.Rect(450, 200, 300, 200)  # rectangular region
    

    Change the direction of movement when the ball hits the bounds:

    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 
    

    See the example:

    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()
    
    0 讨论(0)
  • 2020-12-07 05:41

    it is quite simple. just say if it hits the left or right sides, then multiply the x movement value by -1, and if it hits the top or bottom, then multiply the y movement value by -1

    0 讨论(0)
提交回复
热议问题