Code
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from IPython.display import HTML
# 1. Setup projectile motion parameters
v0 = 20 # Initial velocity (m/s)
angle = 45 # Launch angle (degrees)
g = 9.81 # Gravity (m/s^2)
theta = np.radians(angle)
# Calculate trajectory
t_flight = 2 * v0 * np.sin(theta) / g
t = np.linspace(0, t_flight, 100)
x_max = v0**2 * np.sin(2*theta) / g
y_max = (v0 * np.sin(theta))**2 / (2 * g)
# 2. Create the figure and axis
fig, ax = plt.subplots()
ax.set_xlim(0, x_max * 1.1)
ax.set_ylim(0, y_max * 1.2)
ax.set_xlabel('Distance (m)')
ax.set_ylabel('Height (m)')
ax.set_title(f'Projectile Motion ($v_0={v0}m/s$, $\\theta={angle}^\\circ$)')
line, = ax.plot([], [], 'r-', lw=2)
point, = ax.plot([], [], 'ko')
# 3. Define the update function
def update(frame):
curr_t = t[:frame]
x = v0 * np.cos(theta) * curr_t
y = v0 * np.sin(theta) * curr_t - 0.5 * g * curr_t**2
line.set_data(x, y)
if len(x) > 0:
point.set_data([x[-1]], [y[-1]])
return line, point
# 4. Create the animation
ani = animation.FuncAnimation(
fig, update, frames=len(t), interval=20, blit=True
)
# 4. Render as HTML
animation_video = HTML(ani.to_html5_video())
plt.close(fig) # Prevents the static plot from showing
animation_video