gpt4 book ai didi

python - Pygame - 让 Sprite 朝它所面对的方向移动

转载 作者:太空狗 更新时间:2023-10-30 02:34:59 24 4
gpt4 key购买 nike

我正在制作一个自上而下的赛车游戏,我想让汽车在你按下左右键时旋转(我已经完成了这部分), Sprite 的旋转以度数的形式存储在一个变量中。我希望能够根据它所面对的方向的加速度使其移动。我可以自己弄清楚加速部分,它只是弄清楚那个方向上到底是什么像素。谁能给我一些简单的代码来帮助解决这个问题?

以下是相关类(class)的内容:

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

最佳答案

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

# 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)

关于python - Pygame - 让 Sprite 朝它所面对的方向移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5346874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com