I’m trying to make a script in Python where a certain sprite moves in a parabolic arc in a certain amount of time, where time = t. However I’m bad at this field of mathematics so I don’t know how to properly code this, let alone make it happen in a certain amount of time.
First, I tried to make the y velocity slowly decrease as it reached the peak, and slowly increase after reaching the peak, like so:
# 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
But I couldn’t effectively control time and distance, and it also didn’t look very smooth. Is there an equation I can use to simplify this, and make the object move over the entire parabolic arc in t time?
thereal underscore ethereal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
For your intended purpose assuming constant horizontal velocity should be okay, thus you might use so-called Trajectory Formula which might be written in Python in the following way:
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)
where angle
and velocity
pertains to angle of throw (radians) and initial velocity (meters per second), note that it assumes origin point (double zero) to be lower left corner.
For presentation sake, I created plot of that using seaborn
in the following way:
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')
where angle is 45 degrees and initial velocity 10 meters per second, position is in meters.
If you need more smooth you should decrease step e.g. replace list(range(10))
using [i*0.1 for i in range(100)]
. If you are wondering about 9.8, this is rough gravity acceleration found on Earth.
0