-
Notifications
You must be signed in to change notification settings - Fork 0
/
bounce_anim.py
81 lines (52 loc) · 1.78 KB
/
bounce_anim.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# v = u + 1/2 * a * t^2
#
# The animation pattern is based on the animation tutorial found here:
# http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/
#
class Bounce:
# This class is just a container for the model
def __init__(self, initial_x, initial_y, u_y, dt):
self.v_y = u_y
self.x = initial_x
self.y = initial_y
self.a = -9.8
self.dt = dt
# Iterate
def step(self):
if self.y < 0.0:
self.v_y = -self.v_y
self.v_y = self.v_y + (self.a * self.dt)
self.y = self.y + self.v_y
#------------------------------------------------------------
# set up initial state and global variables
initial_x = 5
initial_y = 0
u_y = 10
dt = 0.01
#------------------------------------------------------------
# Initialize object
bounce = Bounce(initial_x, initial_y, u_y, dt)
#------------------------------------------------------------
# set up figure and animation
fig = plt.figure()
# Limit x-axis to hide stationary points
ax = fig.add_subplot(111, xlim=(1, 10), ylim=(0, 500))
ax.grid()
line, = ax.plot([], [], 'o-', lw=3) #
step_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)
def init():
# Clear frame on each interation
line.set_data([], [])
return line,
def animate(i):
global bounce
bounce.step()
line.set_data(bounce.x, bounce.y)
step_text.set_text('iter: %.1f' % i)
return line, step_text
ani = animation.FuncAnimation(fig, animate, frames=500,
interval=10, blit=True, init_func=init)
plt.show()