3 using System
.Windows
.Controls
;
4 using System
.Windows
.Data
;
5 using System
.Windows
.Documents
;
6 using System
.Windows
.Media
;
7 using System
.Windows
.Navigation
;
8 using System
.Windows
.Shapes
;
10 namespace Microsoft
.Samples
.PerFrameAnimations
13 /// Interaction logic for FollowExample.xaml
16 public partial class FollowExample
: Page
18 private Vector _rectangleVelocity
= new Vector(0,0);
19 private Point _lastMousePosition
= new Point(0, 0);
21 public FollowExample()
24 CompositionTarget
.Rendering
+= UpdateRectangle
;
25 this.PreviewMouseMove
+= UpdateLastMousePosition
;
28 private void UpdateRectangle(object sender
, EventArgs e
)
30 Point location
= new Point(Canvas
.GetLeft(followRectangle
), Canvas
.GetTop(followRectangle
));
32 //find vector toward mouse location
33 Vector toMouse
= _lastMousePosition
- location
;
35 //add a force toward the mouse to the rectangles velocity
36 double followForce
= 0.01;
37 _rectangleVelocity
+= toMouse
* followForce
;
39 //dampen the velocity to add stability
41 _rectangleVelocity
*= drag
;
43 //update the new location from the velocity
44 location
+= _rectangleVelocity
;
47 Canvas
.SetLeft(followRectangle
, location
.X
);
48 Canvas
.SetTop(followRectangle
, location
.Y
);
51 void UpdateLastMousePosition(object sender
, System
.Windows
.Input
.MouseEventArgs e
)
53 _lastMousePosition
= e
.GetPosition(containerCanvas
);