Skip Navigation | ANU Home | Search ANU
The Australian
National University
Computational Science Education Outreach and Training (EOT)
Printer Friendly Version of this Document
VPython Tutorial on Projectile Motion
Vakul Talwar and Stephen Roberts

1  Overview

This tutorial will take you through the motion of a projectile in computational science. You will develop a computer program, using the VPython language, to simulate a simple motion of a ball thrown in the air.

1.1  What is Computational Science?

Computational Science involves using mathematical models and computer programs to simulate and understand the various phenomena occuring around us. A few simple examples are car crash analysis, financial modelling and drug design.
There are three parts to the process of defining and solving a problem in Computational Science:
  1. Find a complete mathematical description of the system that will include all the behaviour you are interested in.
  2. Construct an efficient computer code that solves these equations.
  3. Extract results and predictions that can be compared with real world, with experiments or with other scientific theories.
For more information on Computational Science visit the following website in Australian National University or Stanford University

1.2  What is VPython?

VPython is a programming language that is easy to learn and is well suited to creating simple 3D models and visualisations of physical systems. VPython has three components that you will deal with directly:
  • Python, a programming language invented in 1990 by Guido van Rossem, a Dutch computer scientist. Python is a modern, object-oriented language which is easy to learn.
  • VPython, a 3D graphics module for Python created by David Scherer while he was a student at Carnegie Mellon University. VPython allows you to create and animate 3D objects, and to navigate around in a 3D scene by spinning and zooming, using the mouse.
  • IDLE, an interactive editing environment, written by van Rossem and modified by Scherer, which allows you to enter computer code, try your program, and get information about your program.
This tutorial assumes that Python and Visual are installed on the computer you are using. If you need to install any of these, follow this link to the VPython web page.

2  Simulation of Thrown Ball

We will use VPython to program a simulation of the motion of a ball thrown in air and falling back due of gravity. First we will experiment with the VPython system.

2.1  Starting Visual Python

Start IDLE by clicking on the snake icon on the panel at the bottom of your desktop. A window labelled 'Untitled' should appear. This is the window in which you will type your program.
The window should look something like:

idle.jpg

As the first line of your program, type the following statement:
#######################################################
# Import the Visual and Math Library
#######################################################
from visual import *
from math import *

This statement tells Python to use the Visual Graphics and Math module, needed for creating three dimensional objects and for referencing mathematical functions like sin, cos, pi.

2.2  Creating 3 Dimensional Objects in VPython

Now we will add two more lines to display a scene involving a coloured ball with a thin box as a floor. Type the following statements (you can select the text below and then paste it into IDLE):
#######################################################
# Creates a Floor
#######################################################
floor=box(pos=(0,-10,0),length=40,height=.05,width=20,color=color.yellow)

#######################################################
# Creates a Ball
#######################################################
ball=sphere(pos=(0,0,0),color=color.red)

IDLE will colour different sections of the program to make it easier to read. For example comment lines, which begin with the # symbol are red. The functions box and sphere are 'constructors' for 3D objects. The position of an object's centre is specified in three dimensions using a vector.
Until now we have only 3 lines of actual code, with some comments. Comments have been added for two reasons:
  1. To tell you what the code does.
  2. To designate regions of the code, so that as the code grows it will be easier to describe where to add new features.

2.3  Running the Program

Now run your program by choosing F5 (or by choosing "Run program" from the "Run" menu). When you run the program, two windows will appear. One of the windows is titled "VPython", in which you will see a yellow floor and a red ball above it.
You should see something like this

ball-floor.jpg

In the VPython window, hold down the middle mouse button and move the mouse. You should see that you are able to zoom into and out of the scene. Now try holding down the right mouse button . You should find that you are able to rotate your view of the scene.
You can stop the program by closing the graphics window.

2.4  Objects and attributes

The objects sphere and box, are types that vpython recognises and displays. They have some attributes associated with them (such as position(pos), colour(color) and radius), which can be set when you first define and name the object, otherwise the default values will be used.
You can change the radius attribute of a ball after it has been constructed with the statement:
ball.radius = 0.4

Why don't you play around with the program and try changing the variables pos, length, width and color in the above code.

3  Motion of a Body

Now we want to make the ball move. It is useful to recall some theory on projectile motion.

3.1  Basics of Motion of a Body

The key to a successful computer program is understanding the concept of the problem. In this section we will understand the key concepts like amount of distance travelled by the body, velocity and acceleration it travelled this distance with and the amount of time spent travelling the motion of a body.
Firstly we will like to find out the average velocity or speed of the body. Average velocity is defined as the rate of change in position. Mathematically it can be defined as
vav = x

t
= xx0

tt0
(1)
where vav = Average velocity, x = Final position,   
x0 = Start position,   t = Final time and t0 = Start time.
Secondly we need to find out the average acceleration of the body. Acceleration is defined as the rate of change in velocity. Mathematically it can be defined as,
aav = v

t
= vv0

tt0
(2)
where aav = Average Acceleration,   v = Final velocity,   v0 = Start velocity,   t = Final time and t0 = Start time.
If we take the change in acceleration to be small or non-existent for the motion of a body, then we can say the acceleration to be constant. Under this condition we can drop the subscript and just write a for the acceleration i.e. constant acceleration is similar to the instantaneous acceleration. This supposition is a tremendous gain as it makes deriving formulas in physics much easier. Now we can write Equation (2) with a slight change in notation as,
a = vv0

t0
Which can be written as,
v = v0 + a t
(3)
Here v0 is the velocity at time t = 0 and v is the velocity at any later time t.
Similarly we can find out the position of the particle by using Equation (1) to get
x = x0 + v0 t + 1

2
at2
(4)
Click here to check how this formula was derived.

3.2  Moving the Ball

We have developed code which produces a ball (and a floor), and we have changed attributes of the ball, like size and colour.
We would now like to use the formula we have just derived to make our ball move realistically.
When we throw an object in the air under the gravitational field, the path followed by the object is known as a projectile motion. While the previous section dealt with motion in one dimension, the projectile motion occurs in two dimensional space. In coordinate plane we will represent these two dimensions by the X-axis and Y-axis. The positive X-axis is horizontal and the positive Y-axis is vertically upward.
Let's assume no air resistance. Then the only force acting on the projectile with an object of mass m is it's weight w = mg. The components of the projectile's acceleration is simply
ax = 0,        ay = g,        az = 0
where ax is the horizontal acceleration and ay is the vertical acceleration and az is the acceleration "out of the screen". The negative sign on ay indicates that the acceleration is pointed vertically downwards.
Since the object is moving in three dimensions, then we will also have three components of velocity, represented as,
vx = vcosΘ and vy = vsinΘ and vz = 0
(5)
where vx is velocity in the X - direction, vy is velocity in the Y - direction, vz is velocity in the Z - direction and Θ is angle with the ground at which the ball or object is thrown in the air.
For this case the acceleration components ax and ay are constant. If we know the velocity of a ball at certain point of time, then we can easily find the velocity at a later point in time. Here is how we do it. During a time interval dt, the X-component and Y-component of velocity changes with time, we can calculate this using the following formula,

vx = vx + axdt,       vy = vy+aydt,       vz = vz+azdt
While this is happening, the projectile is moving, so the coordinates are also changing. The X-component and Y-component of position changes with time, we calculate it using the following formula

x = x+vxdt + 1

2
ax dt2,   y = y +vy dt + 1

2
ay dt2,   y = z +vz dt + 1

2
az dt2
We have to specify the starting conditions for the simulation i.e. the initial values of velocity, position and acceleration. Then we step through the calculation to find the position and velocity at the end of each time interval in terms of their values at the beginning, and thus to find the values at the end of any number of intervals.
The curious minds will find the following links insightful for a better understanding of Motion in One dimension and Projectile Motion

3.3  The Code

Since the ball will move in x,y,z components in space, we need to specify all those components. This assigning of values can be done by making velocity, position and acceleration vectors. We call them v_0, x_0, g respectively. We are thinking of the ball as a projectile, which starts with an initial speed v at an angle theta to the horizontal. The initial velocity will be given by the code
theta = pi/4
v = 15
v_0 = vector(v*cos(theta),v*sin(theta),0)

The acceleration vector and initial position of the ball can be given by
x_0 = vector(-8,-8,0)
g = vector(0,-9.8,0)

Add these code snippets to the end of your program.
For moving the ball in space we need to know the updated position of the ball and time elapsed. But we also need a means of checking when to end the simulation i.e. when the ball hits the ground. We can obtain this by typing the following
while ball.pos.y>floor.pos.y:

    # Set number of times loop is repeated per second
    rate(1/dt)
    # Update the time
    t=t+dt
    # Making the ball move
    ball.pos=x_0+v_0*t+0.5*g*t**2

The while loop checks whether the ball position is above the floor and the loop keeps executing till this condition comes true. If the ball position becomes equal to floor position i.e. ball meets the floor, the program stops executing the statements within the while loop.
The code x_0+v_0*t+0.5*a*t**2 calculates the new position of the ball by using the updated value of time and assigns the value to ball.pos.
After adding all the previous lines to the code the program looks like:
################################################
#      Import the visual library
################################################
from visual import *
from math import *

################################################
#      Create a floor and ball
################################################
floor=box(pos=(0,-10,0),length=40,height=.5,width=20,color=color.yellow)
ball=sphere(pos=(0,0,0),color=color.red)

################################################
#     Set the variable values
################################################
theta = pi/4
x_0 = vector(-8, -8, 0)
v = 15
v_0 = vector(v*cos(theta), v*sin(theta), 0)
g = vector(0,-9.8,0)
t=0
dt=.01

#Movement of ball
while ball.pos.y>floor.pos.y:
    # Set number of times loop is repeated per second
    rate(1/dt)
    # Update the time
    t=t+dt
    # Updating ball position
    ball.pos=x_0+v_0*t+0.5*g*t**2

Experiment with different initial position and velocity to see the effect on the ball's path.

4  Numerical Integration

If the acceleration is not constant the integration becomes more difficult. It is not always possible to integrate the equations exactly. Then numerical integration is necessary.
Here is one simple method for solving the motion of an object step by step. This method can cope with acceleration that changes with time and the position of the ball. We will introduce ball.velocity and ball.pos, which will be responsible for calculating and storing the velocity and position respectively, as it changes with time.
Instead of using equation (4) for calculating the new position of the ball, we will use x = x0 + vt which is a simple mathematical formula for updating the position of an object based on it's previous position. In our program we will write this as
    ball.pos=ball.pos+ball.velocity*dt

For calculating the new velocity of the ball, we will use the formula from the equation of motions v = v0 + at, here v is the final/updated velocity and v0 is the starting/old velocity. In our program we will write this as
    ball.velocity=ball.velocity+a*dt

After making the appropriate modifications our code looks like:
################################################
#      Import the visual library
################################################
from visual import *
from math import *

################################################
#      Create a floor and ball
################################################
floor=box(pos=(0,-10,0),length=40,height=.5,width=20,color=color.yellow)
ball=sphere(pos=(0,0,0),color=color.red)

################################################
#     Set the variable values
################################################
theta = pi/4
x_0 = vector(-8, -8, 0)
v = 15
v_0 = vector(v*cos(theta),v*sin(theta),0)
g = vector(0,-9.8,0)
t=0
dt=.01

# Setting ball.velocity and ball.pos equal to the initial value
ball.velocity=v_0
ball.pos = x_0

#Movement of ball
while ball.pos.y>floor.pos.y:
    # Set number of times loop is repeated per second
    rate(1/dt)
    #Update time
    t=t+dt
    ######### Changed part from previous program ########
    ball.pos=ball.pos+ball.velocity*dt
    ball.velocity=ball.velocity+g*dt

Enter and run this program and compare the motion of the ball to the previous example.
Exercise: Try to experiment with different values of theta and check which angle makes the ball go farthest in distance. The winner will get a Mars Bar.

5  Comparison of programs

Till now we have simulated the projectile motion with constant and non-constant acceleration. In the first case we have used equation (4) and in the second case we have used the numerical approximation. We can see the error in the numerical method by drawing out path of motion left by the ball. In the program below we try to do that by using the VPython object 'curve', that joins a list of positions by lines or thin rods. A comparison has been given of both the methods used to simulate the motion of a ball earlier.
################################################
# Import the visual library
################################################
from visual import *
from math import *

# Setting initial position of ball
x_0 = vector(-8,-8,0)

###################################################
# Create a floor
###################################################
floor=box(pos=(0,-10,0),length=40,height=.5,width=20,color=color.yellow)

#####################################################################
# Creating 2 balls and setting there initial position equal to x_0
#####################################################################
ball1=sphere(pos=x_0,color=color.blue)
ball2=sphere(pos=x_0,color=color.red)

###################################################
# Creating the trails for comparison
###################################################
ball1.trail=curve(pos=[ball1.pos],color=ball1.color)
ball2.trail=curve(pos=[ball2.pos],color=ball2.color)

################################################
#     Set the variable values
################################################
theta = pi/4
v=15
v_0=vector(v*cos(theta),v*sin(theta),0)
g=vector(0,-9.8,0)
t=0
dt=.01

#Initialising velocity of Ball 2
ball2.velocity=v_0

#Movement of ball
while ball1.pos.y>floor.pos.y:
    # Set number of times loop is repeated per second
    rate(1/dt)
    #Update time
    t=t+dt
    # Ball 2 motion is calculated with numerical approximation method
    ball2.pos=ball2.pos+ball2.velocity*dt
    ball2.velocity=ball2.velocity+g*dt
    # Trail drawn out for Ball 2
    ball2.trail.append(pos=ball2.pos)
    # Ball 1 motion is calculated with constant acceleration method
    ball1.pos=x_0+v_0*t+0.5*g*t**2
    # Trail drawn out for Ball 1
    ball1.trail.append(pos=ball1.pos)

You should be able to see the difference between the blue and red line is marginal. This difference in trajectory shows the error associated with the numerical approximation method.

6  Air Resistance

In the previous study of the projectile motion, we assumed the effect of air resistance to be negligibly small. But in reality we know that air resistance (often called air drag or simply drag) has a major effect on motion of many objects like tennis balls, baseball, airplanes and bicycle riders.
It's not difficult to include the force of air resistance in the equations for a projectile. But solving these for forces for calculating the position, velocity and shape of the path of the projectile can be complicated. Fortunately it's easy to solve these equations using a computer and we will be using our knowledge from the previous sections for obtaining the desired results.
When we omitted air drag, the only force acting on a projectile with mass m was it's weight w = mg. The components of the projectile were simply
ax = 0,        ay = g
The positive x-axis is horizontal and the positive y-axis is vertical upward. We now introduce the drag acting on the projectile. At the speed of a tossed tennis ball or anything faster, the magnitude F of the air drag force is approximately proportional to the square of the projectile's speed relative to the air:

F* = D v2
The direction of F* is opposite the direction of v, so we can write F* = Dv2 and the components of F* are
F*x = Dvvx,        F*y = Dvvy
Note that each component is opposite in direction to the corresponding component of velocity. Newton's second law gives,

ΣF*x = Dvvx = max and ΣF*y = mgDvvy = may
and the components of acceleration including the effects of both gravity and air drag are
ax = (D/m)vvx and ay = g(D/m)vvy
The constant D depends on the density ρ of air, the surface area A of the body as seen from front and dimensionless constant constant C called the drag coefficient that depends on the shape of the body. Typical values of C for baseballs, tennis balls is in the range from 0.2 to 1.0. In terms of these quantities, D is given by
D = ρC A

2
From the simulation point of view we will have to add new variables in Set the variable values part of the code. Additionally, to make the ball move in air resistance, we will also have to make changes in the Movement of ball part of the code. All these changes have shown below, but for illustration purposes we have considered a baseball with mass m = 0.145kg, radius r = 0.03666m, A = 0.00421, the drag coefficient to be C = 0.5(appropriate for a batted ball or pitched fastball) and the density of air to be rho = 1.2 kg/m3 (appropriate for a ballpark at sea level).
################################################
#      Import the visual and math library
################################################
from visual import *
from math import *

################################################
#      Create a floor and ball
################################################
floor=box(pos=(0,-10,0),length=40,height=.05,width=20,color=color.yellow)
ball=sphere(pos=(0,0,0),color=color.red)

################################################
#     Set the variable values
################################################
x_0 = vector(-8,-8,0)
m = 0.145
A = 0.00421
rho = 1.29
C = 0.5
theta = pi/5
v = 15
v_0=vector(v*cos(theta),v*sin(theta),0)
g=vector(0,-9.8,0)
a = vector(0,0,0)
t=0
dt=.01

#Initializing value of ball.pos, ball.velocity and D
ball.pos = x_0
ball.velocity = v_0
D = (rho*C*A)/2

#Movement of ball
while ball.pos.y>floor.pos.y:
    # Set number of times loop is repeated per second
    rate(1/dt)
    # Update the time
    t=t+dt
    #Update acceleration
    a = g -(D/m)*v*ball.velocity
    # Updating ball position
    ball.pos=ball.pos+ball.velocity*dt+0.5*a*dt**2
    ball.velocity = ball.velocity + a*dt

7  Comparison between Different Air Resistances

In the previous section we simulated the effect of air resistance on a projectile motion. Now from a graphical point of view it will be helpful to observe and compare the effects on a ball when there is:
  1. No air resistance
  2. Air resistance
To do this we take the help of the previous comparison we did and make additional changes. The changes have been shown below,
################################################
# Import the visual and math library
################################################
from visual import *
from math import *

#Setting initial position of ball
x_0 = vector(-8,-8,0)
###################################################
# Create a floor
###################################################
floor=box(pos=(0,-10,0),length=40,height=.5,width=20,color=color.yellow)

#####################################################################
# Creating 2 balls and setting there initial position equal to x_0
#####################################################################
ball1=sphere(pos=x_0,color=color.blue)
ball2=sphere(pos=x_0,color=color.red)

###################################################
# Creating the trails for comparison
###################################################
ball1.trail=curve(pos=[ball1.pos],color=ball1.color)
ball2.trail=curve(pos=[ball2.pos],color=ball2.color)

################################################
#     Set the variable values
################################################
m = 0.145
A = 0.00421
rho = 1.29
C = 0.5
theta = pi/5
v_0=vector(15*cos(theta),15*sin(theta),0)
g=vector(0,-9.8,0)
a = vector(0,0,0)
t=0
dt=.01

#Initialising value of ball2 and D
ball2.velocity=v_0
D = (rho*C*A)/2

#Movement of ball
while ball1.pos.y>floor.pos.y:
    rate(1/dt)
    t=t+dt
    a = g-(D/m)*15*ball2.velocity
    # Ball 2 motion with Air Resistance
    ball2.pos=ball2.pos+ball2.velocity*dt+0.5*a*dt**2
    ball2.velocity=ball2.velocity+a*dt
    # Trail drawn out for Ball 2
    ball2.trail.append(pos=ball2.pos)
    # Ball 1 motion with No Air Resistance
    ball1.pos=x_0+v_0*t+0.5*g*t**2
    # Trail drawn out for Ball 1
    ball1.trail.append(pos=ball1.pos)

8  Conclusion

This tutorial has served to make you understand the motion of a projectile. We have done this by simulating the projectile motion and understood the programming concepts underlying the simulation.
If you have had trouble or run out of time, then here is the code for the projectile motion.
Using these programs as a base, it is possible to create a simulation of the Apollo 13 voyage. Have a look at our Apollo 13 simulation tutorial

9  Helpful Links

  1. Good link on Projectile motion with helpful notes on motion in one dimension and vectors
  2. Link on motion in one dimension