After the introduction and learning, we have mastered how to click on the mouse to move objects, and to achieve 2D characters action animation. So how do you integrate the two perfectly? The content of this section will involve a lot of important techniques and techniques, which is critical.
So again, the foreground XAML stays the same, followed by the first part of the background C #:
int count = 0;
Image Spirit;
Storyboard storyboard;
public Window6() {
InitializeComponent();
Spirit = new Image();
Spirit.Width = 150;
Spirit.Height = 150;
Carrier.Children.Add(Spirit);
Canvas.SetLeft(Spirit, 0);
Canvas.SetTop(Spirit, 0);
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(150);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e) {
Spirit.Source = new BitmapImage((new Uri(@"Player\" + count + ".png", UriKind.Relative)));
count = count == 7 ? 0 : count + 1;
}
The code above basically doesn't change much compared to the previous sections, but it combines the first and fourth sections.
Then look at the second part of C #:
private void Carrier_mouseleftbuttondown (object sender, MouseButtonEventArgs e) {
Point P = e.getposition (Carrier);
Move (p);
}
private void Move (point P) {
Create a mobile animation
Storyboard = new Storyboard ();
Create an X-axis animation
DoubleAnimation doubleanimation = new DoubleAnimation (
Canvas.getleft (Spirit),
P.x,
New Duration (Timespan.fromseconds (1))
);
Storyboard.settarget (DoubleAnimation, Spirit);
Storyboard.settargetproperty (DoubleAnimation, New PropertyPath ("(Canvas.Left)"));
Storyboard. Children.add (DoubleAnimation);
Create a Y-axis animation
DoubleAnimation = new DoubleAnimation (
Canvas.gettop (Spirit),
P.Y,
New Duration (Timespan.fromseconds (1))
);
Storyboard.settarget (DoubleAnimation, Spirit);
Storyboard.settargetproperty (DoubleAnimation, New PropertyPath ("(Canvas.Top)"));
Storyboard. Children.add (DoubleAnimation);
Dynamically loading animations into a resource
if (! Resources.contains ("Rectanimation")) {
Resources.add ("Rectanimation", Storyboard);
}
Animation playback
Storyboard. Begin ();
}
It is easy to see the left mouse button click on the Move () method, this method if you are familiar with the first section will be very good understanding, by combining these two pieces of code, that is, you can achieve the mouse point which leads to where to move, while the protagonist of the animation is always kept running.