>  기사  >  백엔드 개발  >  Vector2 클래스에 의존하지 않고 PyGame에서 튀는 공을 만드는 방법은 무엇입니까?

Vector2 클래스에 의존하지 않고 PyGame에서 튀는 공을 만드는 방법은 무엇입니까?

Mary-Kate Olsen
Mary-Kate Olsen원래의
2024-10-18 20:57:02620검색

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.