Skip to content

Commit af924e7

Browse files
committed
Added mouse interaction.
1 parent b79cd64 commit af924e7

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

examples/animation/rain.py

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@
2121
# Create rain data
2222
n_drops = 50
2323
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)])
2727

2828
# Initialize the raindrops in random positions and with
2929
# random growth rates.
@@ -36,6 +36,10 @@
3636
s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
3737
facecolors='none')
3838

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+
3943

4044
def update(frame_number):
4145
# Get an index which we can use to re-spawn the oldest raindrop.
@@ -48,9 +52,21 @@ def update(frame_number):
4852
# Make all circles bigger.
4953
rain_drops['size'] += rain_drops['growth']
5054

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+
5167
# Pick a new position for oldest rain drop, resetting its size,
5268
# color and growth factor.
53-
rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)
69+
rain_drops['position'][current_index] = new_position
5470
rain_drops['size'][current_index] = 5
5571
rain_drops['color'][current_index] = (0, 0, 0, 1)
5672
rain_drops['growth'][current_index] = np.random.uniform(50, 200)
@@ -59,7 +75,16 @@ def update(frame_number):
5975
scat.set_edgecolors(rain_drops['color'])
6076
scat.set_sizes(rain_drops['size'])
6177
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+
6388

6489
# Construct the animation, using the update function as the animation
6590
# director.

0 commit comments

Comments
 (0)