精灵应该有一个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,这是另一个问题的概念。
希望这有帮助!