Welcome

首页 / 软件开发 / C# / C#开发WPF/Silverlight动画及游戏系列教程(Game Course):(六)完美移动

C#开发WPF/Silverlight动画及游戏系列教程(Game Course):(六)完美移动2010-01-25 博客园 深蓝色右手经过前面的介绍和学习,我们分别掌握了如何点击鼠标让对象移动,并且实现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()方法,该方法大家如果熟悉第一节的话将非常好理解,通过将这两段代码进行合成,即可以实现鼠标点哪主角就向哪移动,同时主角的动画始终保持为跑步状态。