經過前面的介紹和學習,我們分別掌握了如何點擊鼠標讓對象移動,並且實現2D人物的動作動畫。那麼,如何將兩者完美的進行融合呢?這一節的內容將涉及到很多重要的技術及技巧,很關鍵哦。
那麼同樣的,前台xaml還是保持不變,接下來看後台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;
}
上面代碼基本上相對於前面幾節沒有太多改變,只是結合了第一節和第四節的內容。
那麼再看C#第二部分:
private void CarrIEr_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
Point p = e.GetPosition(CarrIEr);
Move(p);
}
private void Move(Point p) {
//創建移動動畫
storyboard = new Storyboard();
//創建X軸方向動畫
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);
//創建Y軸方向動畫
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);
//將動畫動態加載進資源內
if (!Resources.Contains("rectAnimation")) {
Resources.Add("rectAnimation", storyboard);
}
//動畫播放
storyboard.Begin();
}
不難看出鼠標左鍵點擊事件中Move()方法,該方法大家如果熟悉第一節的話將非常好理解,通過將這兩段代碼進行合成,即可以實現鼠標點哪主角就向哪移動,同時主角的動畫始終保持為跑步狀態。