simulate and animate a rocket launch in python

To simulate and animate a rocket launch using Python, we need to simulate the physics of the rocket's motion and animate its movement over time.

We can use Python's matplotlib library to create 2D animations of the rocket's trajectory. We'll use the numpy library for numerical computations.

Here's a high-level overview of the code:

  1. Set up initial conditions (position, velocity, acceleration, mass, thrust, drag, time)
  2. Create empty lists to store the position and time data for the rocket
  3. Loop over time steps and update the rocket's position, velocity, and acceleration using the equations of motion and the rocket's thrust and drag forces
  4. Append the updated position and time data to the respective lists
  5. Use matplotlib to create an animation of the rocket's trajectory through time
main.py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Set up initial conditions
position = np.array([0, 0])  # position vector in meters
velocity = np.array([0, 0])  # velocity vector in meters/second
acceleration = np.array([0, 0])  # acceleration vector in meters/second^2
mass = 100  # mass of the rocket in kg
thrust = np.array([0, 1000])  # thrust force vector in newtons
drag_coefficient = 0.1  # drag coefficient
time = 0  # initial time in seconds

# Create empty lists to store position and time data
position_data = [position]
time_data = [time]

# Loop over time steps
dt = 0.1  # time step in seconds
end_time = 10  # end time of simulation in seconds
while time < end_time:
    # Compute drag force
    speed = np.linalg.norm(velocity)
    drag_force = -drag_coefficient * speed * velocity

    # Compute net force on rocket
    net_force = thrust + drag_force

    # Compute acceleration
    acceleration = net_force / mass

    # Update velocity and position
    velocity += acceleration * dt
    position += velocity * dt

    # Increment time and append data
    time += dt
    position_data.append(position.copy())
    time_data.append(time)

# Animate the rocket's trajectory
fig, ax = plt.subplots()
line, = ax.plot([], [], 'o-')
ax.set_xlim([-10, 1100])
ax.set_ylim([-10, 1100])
ax.set_xlabel('X position (m)')
ax.set_ylabel('Y position (m)')
ax.set_title('Rocket Launch')

def update(frame):
    data = np.concatenate([position_data[:frame], np.zeros((len(position_data)-frame, 2))])
    line.set_data(data[:,0], data[:,1])
    return line,

ani = FuncAnimation(fig, update, frames=len(position_data), interval=50)
plt.show()
1695 chars
57 lines

This code should produce an animated plot of a rocket launching from (0, 0) and traveling in the positive x-direction with a constant thrust force of 1000 newtons. You can tweak the initial conditions and physics equations to simulate different rocket launches.

gistlibby LogSnag