Pygame中如何让物体在一定时间内按抛物线弧线移动?

问题描述 投票:0回答:1

我正在尝试用Python编写一个脚本,其中某个精灵在一定的时间内以抛物线弧移动,其中时间= t。然而我在这个数学领域很糟糕,所以我不知道如何正确地编码,更不用说让它在一定的时间内发生了。

首先,我尝试让 y 速度在达到峰值时缓慢减小,在达到峰值后缓慢增加,如下所示:

# In pygame, the higher you go, the lower the y value. Smaller x values are to the left.
yvel = 1
if y > peak:
    y - yvel
    yvel -= 0.1
    x -= 2
else:
    y + yvel
    yvel += 0.1
    x -= 2

但是我无法有效控制时间和距离,而且看起来也不是很顺利。有没有一个方程可以用来简化这个过程,并使物体在 t 时间内移动整个抛物线?

python math pygame
1个回答
0
投票

出于您的预期目的,假设恒定的水平速度应该没问题,因此您可以使用所谓的轨迹公式,它可能以

python
镂空方式写成

import math
def height(x, angle, velocity, gravity=9.8):
    return x * math.tan(angle) - (gravity * x ** 2) / (2 * velocity ** 2 * math.cos(angle) ** 2)

其中角度和速度与投掷角度(弧度)和初始速度(米每秒)有关,请注意,它假设原点(双零)位于左下角。

为了演示目的,我使用以下方式

seaborn
创建了该图

import seaborn as sns

pos_x = list(range(10))
pos_y = [height(x, math.radians(45), 10) for x in pos_x]

sns.lineplot(x=pos_x, y=pos_y).get_figure().savefig('trajectory.png')

角度为 45 度,初速度为 10 米每秒,位置单位为米

trajectory plot

如果您需要更平滑,您应该减少步长,例如使用

list(range(10))
替换
[i*0.1 for i in range(100)]
,如果您想知道 9.8,这是在 Sol III 发现的粗略重力加速度。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.