Welcome

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

C#开发WPF/Silverlight动画及游戏系列教程(Game Course):(十五)2010-01-26 博客园 深蓝色右手C#开发WPF/Silverlight动画及游戏系列教程(Game Course):(十五) 精灵控件横空出世!②

紧接着上一节,我们打开QXSpirit.xaml.cs文件。在游戏设计中,为了能够轻易控制及管理精灵的各项属性及功能等,我赋予每个精灵一个专属线程,它在精灵的使用中起到关键作用:

public QXSpirit() {
InitializeComponent();
InitThread(); //初始化精灵线程
}
DispatcherTimer Timer = new DispatcherTimer();
private void InitThread() {
Timer.Tick += new EventHandler(Timer_Tick);
Timer.Start();
}
//精灵线程间隔事件
int count = 1;
private void Timer_Tick(object sender, EventArgs e) {
Body.Source = new BitmapImage((new Uri(ImageAddress + count + ".png", UriKind.Relative)));
count = count == 7 ? 0 : count + 1;
}

DispatcherTimer线程的创建在前面的章节中见得不要太多,这里不再累述了。那为何要在精灵控件中配置一个线程呢?打这样一个比方吧:我们可以把精灵比做一个人,它的生命就好比这个线程,每个人只有一条命,在精子与卵子结合之后(控件的初始化中创建),生命即开始鲜活(创建后即启动)简单说就是“命悬一线”啦。汗一个…。目前该线程与前面章节中的一样,暂时只做精灵动作图片切用(Timer_Tick()),至于其他功用,我将在后面的章节中进行讲解。

赋予了精灵生命以后,接着需要培养它的性格,让它有更多的能力、更多的属性。当然,大家首先迫切想要实现的就是前两节遗留下来关于精灵的X,Y属性。那么先来看代码:

//精灵X坐标(依赖属性)
public double X {
get { return (double)GetValue(XProperty); }
set { SetValue(XProperty, value); }
}
public static readonly DependencyProperty XProperty = DependencyProperty.Register(
"X", //属性名
typeof(double), //属性类型
typeof(QXSpirit), //属性主人类型
new FrameworkPropertyMetadata(
(double)0, //初始值0
FrameworkPropertyMetadataOptions.None, //不特定界面修改
//不需要属性改变回调
null,//new PropertyChangedCallback(QXSpiritInvalidated),
//不使用强制回调
null

);
//精灵Y坐标(依赖属性)
public double Y {
get { return (double)GetValue(YProperty); }
set { SetValue(YProperty, value); }
}
public static readonly DependencyProperty YProperty = DependencyProperty.Register(
"Y",
typeof(double),
typeof(QXSpirit),
new FrameworkPropertyMetadata(
(double)0,
FrameworkPropertyMetadataOptions.None,
null,
null

);