스프라이트에는 xVel
및 yVel
개의 변수가 있어야합니다. 이 변수는 매 프레임마다 x
및 y
개의 변수를 변경합니다. 스프라이트는 각각 x
및 y
변수에서 화면에 그려집니다.
class Sprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.xVel = 0
self.yVel = 0
self.x = 100
self.y = 100
# Continue method
def update(self):
self.x += xVel
self.y += yVel
# Continue method
다음은 스프라이트 충돌 처리 코드의 모습입니다.
if sprite1.yVel == 0 and sprite2.yVel == 0:
# This is when the sprites are not travelling up or down the y axis
sprite1.xVel = -sprite1.xVel
sprite2.xVel = -sprite2.xVel
if sprite1.xVel == 0 and sprite2.xVel == 0:
# This is when the sprites are not travelling left or right on the x
# axis
sprite1.yVel = -sprite1.yVel
sprite2.yVel = -sprite2.yVel
이 코드는 4 방향 이동을위한 코드입니다. xVel
변수를 -xVel
과 같게 설정하면 반대 방향으로 이동합니다. 변수는 yVel
에도 동일하게 적용됩니다. 객체를 사용하는 한 전역 변수를 변경할 필요가 없습니다.
또한 플레이어가 왼쪽 또는 오른쪽으로 이동하는 경우 yVel == 0
입니다. 플레이어가 위 또는 아래로 여행하는 경우 xVel == 0
.
스프라이트의 이동 속도는 프레임 속도에 따라 다릅니다. 이 문제를 해결하는 방법은 다른 질문의 개념 인 deltatime을 사용하는 것입니다.
희망이 도움이되었습니다!
귀하의 질문에 약간의 불확실성이 있습니다. 원하는 행동을 정확하게 묘사하십시오. 그리고 코드를 보여주십시오 (최소한의 완전하고 검증 가능한 예제 (https://stackoverflow.com/help/mcve)). – skrx