Pygame - 如何使一个精灵沿着它所面向的方向移动

5
我将制作一款自上而下的赛车游戏,并希望在按下左右键时使汽车旋转(我已经完成了这部分),精灵的旋转以度数存储在变量中。我想能够根据加速度使其朝着面对的方向移动。我可以自己解决加速度部分,只是需要找出确切的像素方向。有人可以给我一些简单的代码来帮助吗?
以下是相关类的内容:
def __init__(self, groups):
    super(Car, self).__init__(groups)
    self.originalImage = pygame.image.load(os.path.join("Data", "Images", "Car.png")) #TODO Make dynamic
    self.originalImage.set_colorkey((0,255,0))
    self.image = self.originalImage.copy() # The variable that is changed whenever the car is rotated.

    self.originalRect = self.originalImage.get_rect() # This rect is ONLY for width and height, the x and y NEVER change from 0!
    self.rect = self.originalRect.copy() # This is the rect used to represent the actual rect of the image, it is used for the x and y of the image that is blitted.

    self.velocity = 0 # Current velocity in pixels per second
    self.acceleration = 1 # Pixels per second (Also applies as so called deceleration AKA friction)
    self.topSpeed = 30 # Max speed in pixels per second
    self.rotation = 0 # In degrees
    self.turnRate = 5 # In degrees per second

    self.moving = 0 # If 1: moving forward, if 0: stopping, if -1: moving backward


    self.centerRect = None

def update(self, lastFrame):
    if self.rotation >= 360: self.rotation = 0
    elif self.rotation < 0: self.rotation += 360

    if self.rotation > 0:
        self.image = pygame.transform.rotate(self.originalImage.copy(), self.rotation)
        self.rect.size = self.image.get_rect().size
        self.center() # Attempt to center on the last used rect

    if self.moving == 1:
        self.velocity += self.acceleration #TODO make time based

    if self.velocity > self.topSpeed: self.velocity = self.topSpeed # Cap the velocity
2个回答

6

三角函数:获取坐标的公式为:

# cos and sin require radians
x = cos(radians) * offset
y = sin(radians) * offset

您使用速度来进行偏移。(这意味着负速度会向后驱动)。因此:
def rad_to_offset(radians, offset): # insert better func name.
    x = cos(radians) * offset
    y = sin(radians) * offset
    return [x, y]

loop_update类似于:

# vel += accel
# pos += rad_to_offset( self.rotation, vel )

math.cos,math.sin:使用弧度

将旋转存储为弧度更加简单。如果您想将速度等定义为度数,则仍然可以这样做。

# store radians, but define as degrees
car.rotation_accel = radians(45)
car.rotation_max_accel = radians(90)

非常有用且讲解得很清楚。这对我帮助很大! - ReinstateMonica3167040

1

我没有比指向这个教程(*)更好的方法了。特别是,第一部分解释了如何进行旋转并使精灵朝特定方向移动。


(*) 这是一个不要脸的广告 :-) 但与问题非常相关。

是的,那并没有太大帮助,我想要的不仅仅是8轴运动。我需要360轴运动,也就是说它需要进行动态计算。 - JT Johnson
只要您使用相同的技术,就可以实现任意轴的运动 - 数学是相同的。 - Eli Bendersky
1
不鼓励仅提供链接的答案。请在您的答案中引用相关部分的链接。 - ReinstateMonica3167040

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接