simulate and animate a rocket launch in 3d in python

To simulate and animate a rocket launch in 3D in Python, we can use a combination of different libraries such as numpy, matplotlib, and mayavi. Here's an example code that demonstrates how to simulate and animate a rocket launch in 3D in Python:

main.py
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from mayavi import mlab

# Define constants
m = 10000  # rocket mass in kg
g = 9.81  # acceleration due to gravity in m/s^2
rho = 1.22  # density of air in kg/m^3
Cd = 0.5  # drag coefficient
A = 10  # cross-sectional area of rocket in m^2
ve = 3250  # exhaust velocity in m/s
dt = 0.1  # time step in seconds
t_max = 100  # simulation time in seconds

# Define initial conditions
v = np.array([0, 0, 0])  # velocity in m/s
r = np.array([0, 0, 0])  # position in m
t = 0  # initial time in s
A_vec = np.array([0, 0, A])  # cross-sectional area vector

# Create animation
mlab.figure()

# Loop through simulation
while t < t_max:
    m -= ve * dt / g  # update rocket mass
    if m < 0:
        m = 0

    # Calculate net force
    F = np.array([0, 0, -m * g])  # force due to gravity
    v_abs = np.linalg.norm(v)
    F_drag = -0.5 * rho * Cd * A * v_abs * v * A_vec  # force due to drag
    F_net = F + F_drag  # net force

    # Update velocity and position
    v += F_net / m * dt
    r += v * dt

    # Plot rocket in 3D
    x, y, z = r
    mlab.points3d(x, y, z, scale_factor=100, color=(1, 1, 1))

    # Update time
    t += dt
    
    # Increase animation speed by decreasing the below number
    n_int = 4
    if t%n_int==0:
        mlab.view(azimuth=10*t/dt, elevation=70, distance=5e5-5e4*t/dt)

# Show animation
mlab.show()
1427 chars
55 lines

This code simulates a rocket launch in 3D by calculating the net force on the rocket at every time step using the equations of motion. The position and velocity of the rocket are updated accordingly, and the rocket is plotted in 3D using mayavi. The animation shows the rocket lift off and ascend into the sky, with the camera following its trajectory.

gistlibby LogSnag