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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!