Vector2 クラスに依存せずに PyGame でバウンドするボールを作成するにはどうすればよいですか?

Mary-Kate Olsen
リリース: 2024-10-18 20:57:02
オリジナル
619 人が閲覧しました

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 Rect オブジェクト。これにより、ボールが移動できる範囲が定義されます。

<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>
ログイン後にコピー

この例には、ボールが移動したり壁で跳ね返ったりする範囲を表す赤い四角形が含まれています。

以上がVector2 クラスに依存せずに PyGame でバウンドするボールを作成するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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