Skip to content

Instantly share code, notes, and snippets.

@strugee
Last active December 16, 2015 19:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save strugee/5cdce77f397eba804d19 to your computer and use it in GitHub Desktop.
glow buggy
# GlowScript 1.1 VPython
# Borrowed from Frank Noschese: http://www.glowscript.org/#/user/Mr._Noschese/folder/My_Programs/program/CVBuggies/edit
# objects
buggy1 = box(pos=vector(-200,9,0), size=vector(20,12,8), color=color.blue)
buggy2 = box(pos=vector(0,9,0), size=vector(20,12,8), color=color.red)
track = box(pos=vector(-100,10,-5), size=vector(620,25,2), color=color.white)
attach_trail(buggy1, type='spheres')
attach_trail(buggy2, type='spheres')
# collision type
elasticity = 'perfectly inelastic'
# initial values
v1 = vector(5,0,0)
v2 = vector(-5,0,0)
# mass
m1 = 3
m2 = 2
# acceleration
a1 = vector(0,0,0)
a2 = vector(0,0,0)
# state
dt = 1
time = 0
vf = None
# utility functions
def momentum(m, v):
return m*v
def kineticEnergy(m, v):
return (1/2)*m*v*v
def format_output():
'''
Returns a tab-delimited string with the following values:
- Time
- iHat position of buggy 1
- iHat position of buggy 2
- iHat velocity of buggy 1
- iHat velocity of buggy 2
- Momentum of buggy 1
- Momentum of buggy 2
- Momentum of final system
- Kinetic energy of buggy 1
- Kinetic energy of buggy 2
- Kinetic energy of final system
'''
out = str(time) + '\t'
out += str(buggy1.pos.x) + '\t'
out += str(buggy2.pos.x) + '\t'
out += str(v1.x) + '\t'
out += str(v2.x) + '\t'
out += str(momentum(m1, v1).x) + '\t'
out += str(momentum(m2, v2).x) + '\t'
if vf:
out += str(momentum(m1 + m2, vf).x) + '\t'
else:
out += '0\t'
out += str(kineticEnergy(m1, v1.x)) + '\t'
out += str(kineticEnergy(m2, v2.x)) + '\t'
if vf:
out += str(kineticEnergy(m1 + m2, vf.x)) + '\t'
else:
out += '0\t'
return out
def colliding():
'''Returns a boolean indicating whether we've collided'''
return buggy1.pos.x + 20 >= buggy2.pos.x
def finalVelocity(m1, m2, v1, v2):
'''Get the final velocity after a perfectly inelastic collision'''
return (m1*v1 + m2*v2)/(m1+m2)
while time < 40:
rate(10)
buggy1.pos = buggy1.pos + v1*dt + 0.5*a1*dt*dt
buggy2.pos = buggy2.pos + v2*dt + 0.5*a2*dt*dt
v1 = v1 + a1*dt
v2 = v2 + a2*dt
# If we've already collided perfectly inelastically
if vf:
v1 = vf
v2 = vf
time = time + dt
if colliding():
if elasticity == 'perfectly elastic':
# When we collide, flip the velocity
v1 = -v1
v2 = -v2
if elasticity == 'perfectly inelastic':
# When we collide, compute the final post-collision velocity
vf = finalVelocity(m1, m2, v1, v2)
v1 = vf
v2 = vf
a1 = vector(0,0,0)
a2 = vector(0,0,0)
print(format_output())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment