21
21
# Create rain data
22
22
n_drops = 50
23
23
rain_drops = np .zeros (n_drops , dtype = [('position' , float , 2 ),
24
- ('size' , float , 1 ),
25
- ('growth' , float , 1 ),
26
- ('color' , float , 4 )])
24
+ ('size' , float , 1 ),
25
+ ('growth' , float , 1 ),
26
+ ('color' , float , 4 )])
27
27
28
28
# Initialize the raindrops in random positions and with
29
29
# random growth rates.
36
36
s = rain_drops ['size' ], lw = 0.5 , edgecolors = rain_drops ['color' ],
37
37
facecolors = 'none' )
38
38
39
+ # Keep hold of the mouse coordinates (x, y, animation_age) so that we can seed
40
+ # more dropplets near the mouse.
41
+ mouse_info = [None , None , None ]
42
+
39
43
40
44
def update (frame_number ):
41
45
# Get an index which we can use to re-spawn the oldest raindrop.
@@ -48,9 +52,21 @@ def update(frame_number):
48
52
# Make all circles bigger.
49
53
rain_drops ['size' ] += rain_drops ['growth' ]
50
54
55
+
56
+ # Compute a new position for the next raindrop. Base this on the
57
+ # last mouse position, otherwise just use the original uniform
58
+ # distribution.
59
+ mouse_x , mouse_y , age = mouse_info
60
+ if age is not None and age < 1000 and age % 3 == 0 :
61
+ mouse_info [2 ] += 1
62
+ new_position = [np .random .normal (loc = mouse_x , scale = 0.15 ),
63
+ np .random .normal (loc = mouse_y , scale = 0.15 )]
64
+ else :
65
+ new_position = np .random .uniform (0 , 1 , 2 )
66
+
51
67
# Pick a new position for oldest rain drop, resetting its size,
52
68
# color and growth factor.
53
- rain_drops ['position' ][current_index ] = np . random . uniform ( 0 , 1 , 2 )
69
+ rain_drops ['position' ][current_index ] = new_position
54
70
rain_drops ['size' ][current_index ] = 5
55
71
rain_drops ['color' ][current_index ] = (0 , 0 , 0 , 1 )
56
72
rain_drops ['growth' ][current_index ] = np .random .uniform (50 , 200 )
@@ -59,7 +75,16 @@ def update(frame_number):
59
75
scat .set_edgecolors (rain_drops ['color' ])
60
76
scat .set_sizes (rain_drops ['size' ])
61
77
scat .set_offsets (rain_drops ['position' ])
62
-
78
+
79
+
80
+ def on_mouse_over (event ):
81
+ if event .inaxes :
82
+ mouse_info [0 ] = event .xdata
83
+ mouse_info [1 ] = event .ydata
84
+ mouse_info [2 ] = 0
85
+
86
+ cid = fig .canvas .mpl_connect ('motion_notify_event' , on_mouse_over )
87
+
63
88
64
89
# Construct the animation, using the update function as the animation
65
90
# director.
0 commit comments