问题描述
我正在尝试制作一个自上而下的赛车游戏,你必须按向上键向前移动,按左右键来改变汽车的角度。我知道这背后有一些数学原理,但我绝对不了解它们。我怎样才能在 pygame 中做到这一点?
解决方法
您可以使用 pygame.math 中的 Vector2。在您的汽车类中,您必须添加两个属性:
-
velocity = pygame.math.Vector2(0,speed)
你的车开得有多快 -
direction = 0
汽车的方向
对您的游戏进行编程,以便在按左键时direction -= dirspeed
,反之亦然。在更新时,您可以执行 self.current_velocity = velocity.rotate(direction)
。 Vector2s 就像元组一样工作,这意味着您可以执行以下操作:
x = velocity.x
y = velocity.y
它背后可能有更多的数学知识,但我希望这会有所帮助。
,我认为你的意思是确定玩家移动的速度。
要计算速度,您可以使用数学库中的正弦和余弦:
X Velocity = Speed of the player * math.cos(Angle that you want to move to)
Y Velocity = Speed of the player * math.sin(Angle that you want to move to)
有关更多信息,我会去https://courses.lumenlearning.com/boundless-physics/chapter/projectile-motion/ 或搜索速度预测物理学的工作原理。