Saturday, January 9, 2010

AP Physics: A Bouncing Ball in Visual Python

I used CamStudio (on a PC) to record a video of a physics simulation (a bouncing ball) that I made using Visual Python.

Here's the video.

Here is the code:

from __future__ import division # makes sure is decimal and not integer
from visual import *

# cast of characters
floor = box(length=30, height=0.5, width=30, color=color.blue) # the apparent ground
ball = sphere(pos=(-15,20,0), radius = 0.5, material = materials.wood) # distances in meters
ball.trail = curve(color=ball.color) # creates a trail following the ball

# initial conditions
ball.velocity = vector(2,0,0) # m/s
F_fric = vector(0,0,0) # N

# constants of simulation - note upward and rightward are + (positive) in sign
g = 9.8 # magnitude of gravitational field in m/s^2
m = 1 # mass kilograms
dt = 0.01 # time step in seconds
b = 0.01 # drag force constant, where F_drag = -bv^n
n = 1.0 # drag force power, where (again) F_drag = -bv^n
coeff_restitution = 0.70 # fractional decrease in speed at each collision
coeff_friction = 0.15 # coefficient of rolling friction between ball and ground

while 1:
rate(100)
# forces acting on the object
F_grav = vector(0,-m*g,0) # gravitational force
F_drag = - norm(ball.velocity) * b * math.pow(ball.velocity.mag, n)
F_net = F_grav + F_drag + F_fric
# note friction force is handled below because we need to know if we've reached the floor

# kinematics
a = F_net / m
ball.pos = ball.pos + ball.velocity*dt
ball.trail.append(pos=(ball.x,ball.y,ball.z), retain = 200) # update trail behind ball
if ball.y - ball.radius <= floor.pos.y + (floor.height/2.0): # if ball reaches floor
F_fric = - norm(ball.velocity) * coeff_friction * m * g # only friction if rolling on ground
ball.velocity.y = -ball.velocity.y * coeff_restitution # loses KE on collision; flip y-velocity
ball.pos = ball.pos + ball.velocity*dt # avoids a problem I had with "sticking" -- kluge
else: # if ball is still in the air
F_fric = vector(0,0,0) # no friction with ground
ball.velocity = ball.velocity + a*dt # do ordinary kinematics

No comments:

Post a Comment