PyGame でボールが境界を越えないようにする方法は?

Patricia Arquette
リリース: 2024-10-18 21:00:30
オリジナル
297 人が閲覧しました

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!