Projectile motion with VPython
Projectile motion is a form of motion experienced by an object thrown into the air at some angle. Since it is a two-dimensional motion, it is characterized by two components:
Horizontal motion: The motion of the object along the x-axis is the horizontal motion which is given by the following equation:
where
Vertical motion: The motion of the object along the y-axis is the vertical motion which is given by the following equation:
where
Code
We can simulate the projectile motion using the VPython library. To execute the provided code, you have to follow below mentioned steps:
The sample code is as follows:
from vpython import *
g = 9.8 # Acceleration due to gravity (m/s^2)
# Scene setup
scene = canvas(width=1200, height=600, center=vec(0, 10, 0), background=color.white)
ground = box(pos=vec(-10, 0, 0), size=vec(50, 0.2, 2), color=color.gray(0.7))
# Projectile properties
ball = sphere(pos=vec(-20, 0, 0), radius=1.0, color=color.blue)
velocity = 20.0 # Initial velocity (m/s)
angle = 65.0 # Launch angle (degrees)
angle_rad = radians(angle)
v0x = velocity * cos(angle_rad)
v0y = velocity * sin(angle_rad)
# Time step and total time
dt = 0.01
# Simulation loop
while ball.pos.y >= 0:
# Limit the animation speed
rate(100)
# Update position and velocity
ball.pos.x += v0x * dt
ball.pos.y += v0y * dt - 0.5 * g * dt**2
# Update velocity components
v0y -= g * dtCode explanation
Line 1: Importing the VPython library.
Line 2: Storing the gravitational acceleration in the variable
g.Line 6: The
scenevariable stores acanvasobject, which creates a window of dimensionsand a white background color. The center of the window is points below the origin in the y-axis. Line 7: The
groundvariable stores aboxobject, which creates a road-like structure the projectile will be launched from and land at.Line 10: The
ballvariable stores asphereobject, creating a blue three-dimensional object that takes off from thegroundobject.Line 11–13: The initial velocity (
) and angle ( ) are stored in the velocityandanglevariables respectively. Theangleis then converted to theusing the radians()method and stored in theangle_radvariable.Line 14–15: The x and y components of the initial velocity are stored in the
v0xandv0yvariables respectively.Line 18: The
dtvariable stores the instantaneous time of the projectile motion.Line 21: The while loop here will keep executing until the vertical displacement gets zero i.e., the ball hits the ground.
Line 23: Sets frames per second.
Line 25–26: The horizontal and vertical position of the ball is getting updated with each iteration of the loop.
Line 29: The vertical velocity is getting updated because the speed decreases gradually in the projectile motion as the ball approaches the highest point in its trajectory. After that point, the speed increases until the ball hits the ground.
Note: Learn how to simulate a simple pendulum in VPython.
Free Resources