Pygame - 让精灵朝它面向的方向移动

5 投票
2 回答
12900 浏览
提问于 2025-04-16 13:56

我正在制作一个俯视视角的赛车游戏,想要让汽车在按下左右键时旋转(这部分我已经做完了),汽车的旋转角度是以度数存储在一个变量里。我希望能够让汽车根据它面朝的方向来加速移动。我可以自己搞定加速的部分,关键是要弄清楚具体哪个像素是在那个方向上。有没有人能给我一些简单的代码来帮助我解决这个问题?

以下是与此相关的类的内容:

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 个回答

1

我觉得最好的办法就是推荐你去看看这个教程 (*). 特别是第一部分,里面讲了怎么旋转和让角色在特定方向上移动。


(*) 这是我个人的推荐 :-) 但跟你的问题非常相关。

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)

撰写回答