如何在 PyGame 中製作彈跳球而不依賴 Vector2 類?

Mary-Kate Olsen
發布: 2024-10-18 20:57:02
原創
618 人瀏覽過

How to Make a Bouncing Ball in PyGame without Relying on Vector2 Class?

在沒有Vector2 類的PyGame 中彈跳球

在這種情況下,您遇到了PyGame 腳本中球從牆壁彈起的問題,特別是與頂壁碰撞時。儘管您進行了研究,但您仍然遇到挑戰。

巢狀循環與替代方法:

主要問題是多個巢狀循環。相反,在應用程式循環中連續移動球。

<code class="python">box.y -= box.vel_y        
box.x += box.vel_x</code>
登入後複製

定義矩形區域:

使用PyGame 矩形物件。這將定義球可以移動的區域。

<code class="python">bounds = window.get_rect() # full screen</code>
登入後複製

或者,您可以指定特定的矩形區域:

<code class="python">bounds = pygame.Rect(450, 200, 300, 200) </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">import pygame

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 中製作彈跳球而不依賴 Vector2 類?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!