上一篇:
C#开发WPF/Silverlight动画及游戏系列教程(Game Course):(八) 完美实现A*寻径动态动画本节将运用前两节的知识到实际的2D游戏人物在地图上移动中,同时也算是对前面八节的内容进行一次综合运用吧。
那么先从最底层的地图讲起。首先我将一张地图添加进游戏窗口中,这里我同样使用Image控件:
- Image Map = new Image();
- private void InitMap() {
- Map.Width = 800;
- Map.Height = 600;
- Map.Source = new BitmapImage((new Uri(@"Map\Map.jpg", UriKind.Relative)));
- Carrier.Children.Add(Map);
- Map.SetValue(Canvas.ZIndexProperty, -1);
- }
复制代码我将一个800*600名叫Map.jpg的地图图片添加进项目Map文件夹中,然后将它的Canvas.Zindex属性设置为-1,这样它就相当于地图背景的作用了。有了这张地图以后,我们需要对它进行障碍物设置:
附件:
1.jpg 从上图可以看到,理想的状态下,障碍物为我用蓝色填充的区域,这是理想状态下障碍物的设置。但是实际运用中,就拿本教程来讲,因为GridSize设置为20,那么我们最终得到的障碍物将是这样的:
附件:
3.jpg 从上图可以看到,每个绿色格子代表一个20*20像素的障碍物,只能说勉强达到描绘障碍物的效果吧。从而又验证了我们上一节所讲到的GridSize越小,定位将越精确,难道不是至理名言吗!
有了这个思路,接下来我用了3个循环算法实现了左部分的障碍物设定:
- //构建障碍物
- for (int y = 12; y <= 27; y++) {
- for (int x = 0; x <= 7; x++) {
- //障碍物在矩阵中用0表示
- Matrix[x, y] = 0;
- rect = new Rectangle();
- rect.Fill = new SolidColorBrush(Colors.GreenYellow);
- rect.Opacity = 0.3;
- rect.Stroke = new SolidColorBrush(Colors.Gray);
- rect.Width = GridSize;
- rect.Height = GridSize;
- Carrier.Children.Add(rect);
- Canvas.SetLeft(rect, x * GridSize);
- Canvas.SetTop(rect, y * GridSize);
- }
- }
- int move = 0;
- for (int x = 8; x <= 15; x++) {
- for (int y = 12; y <= 18; y++) {
- Matrix[x, y - move] = 0;
- rect = new Rectangle();
- rect.Fill = new SolidColorBrush(Colors.GreenYellow);
- rect.Opacity = 0.3;
- rect.Stroke = new SolidColorBrush(Colors.Gray);
- rect.Width = GridSize;
- rect.Height = GridSize;
- Carrier.Children.Add(rect);
- Canvas.SetLeft(rect, x * GridSize);
- Canvas.SetTop(rect, (y - move) * GridSize);
- }
- move = x % 2 == 0 ? move + 1 : move;
- }
- int start_y = 4;
- int end_y = 10;
- for (int x = 16; x <= 23; x++) {
- for (int y = start_y; y <= end_y; y++) {
- Matrix[x, y + move] = 0;
- rect = new Rectangle();
- rect.Fill = new SolidColorBrush(Colors.GreenYellow);
- rect.Opacity = 0.3;
- rect.Stroke = new SolidColorBrush(Colors.Gray);
- rect.Width = GridSize;
- rect.Height = GridSize;
- Carrier.Children.Add(rect);
- Canvas.SetLeft(rect, x * GridSize);
- Canvas.SetTop(rect, (y + move) * GridSize);
- }
- start_y = x % 3 == 0 ? start_y + 1 : start_y;
- end_y = x % 3 == 0 ? end_y - 1 : end_y;
- }
复制代码