首頁  >  文章  >  後端開發  >  如何在 PyGame 中防止球越界?

如何在 PyGame 中防止球越界?

Patricia Arquette
Patricia Arquette原創
2024-10-18 21:00:30297瀏覽

How to Prevent Ball from Crossing Boundaries in PyGame?

如何使用PyGame 讓球從牆壁彈開

問題

在PyGame 中,當以下情況時如何防止球進入牆內它擊中了一個?

巢狀循環:

問題是由於使用多個巢狀循環而引起的。在應用程式循環中處理移動會更有效。

<code class="python">while run:                     
    # Handle movement continuously
    box.y -= box.vel_y        
    box.x += box.vel_x</code>

邊界定義:

使用pygame.Rect 物件定義球運動的長方形區域:

<code class="python">bounds = window.get_rect() # full screen
bounds = pygame.Rect(450, 200, 300, 200)  # rectangular region</code>

處理:

球與邊界相交時更新球方向:
<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>

以上是如何在 PyGame 中防止球越界?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn