如何在Cocos2D游戏中实现A*寻路算法(二)

前端之家收集整理的这篇文章主要介绍了如何在Cocos2D游戏中实现A*寻路算法(二)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处.
如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;)


免责申明:本博客提供的所有翻译文章原稿均来自互联网,仅供学习交流之用,请勿进行商业用途。同时,转载时不要移除本申明。如产生任何纠纷,均与本博客所有人、发表该翻译稿之人无任何关系。谢谢合作!

猫咪迷宫和A*概述

正如你所看到的,现在当你在地图某处触摸的时候,猫咪将会跳到你触摸方向的相邻瓦格中去.

我们想要修改为猫咪连续移动直到你点击的位置,就像一些RPG或者点击的探险游戏一样.

让我们看一下当前触摸处理代码是如何工作的.如果你打开HelloWorldLayer,你将发现其像下面代码一样实现触摸回调:

  1. - (void)registerWithTouchDispatcher {
  2. [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
  3. }
  4.  
  5. - (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
  6.  
  7. if (_gameOver) return NO;
  8.  
  9. CGPoint touchLocation = [_tileMap convertTouchToNodeSpace:touch];
  10. [_cat moveToward:touchLocation];
  11. return YES;
  12. }

你可以看到它仅仅调用了cat sprite中的一个方法,让猫咪在地图上朝着触摸的点方向去移动.

所以我们将去修改CatSprite.m中的以下方法去找寻到目的点的最短路径,如下所示:

  1. - (void)moveToward:(CGPoint)target {
  2. // Figure out the shortest path to the target,and start following it!
  3. }

创建ShortestPathStep类

让我们从创建一个描述路径中的step的内部类中开始.在我们的例子中,这是一个瓦块,并且它的F,G和H分值都由A*算法来计算.

So添加以下代码到CatSprite.m的开头(在CatSprite的@implementation之上):

  1. // A class that represents a step of the computed path
  2. @interface ShortestPathStep : NSObject
  3. {
  4. CGPoint position;
  5. int gscore;
  6. int hscore;
  7. ShortestPathStep *parent;
  8. }
  9.  
  10. @property (nonatomic,assign) CGPoint position;
  11. @property (nonatomic,assign) int gscore;
  12. @property (nonatomic,assign) int hscore;
  13. @property (nonatomic,assign) ShortestPathStep *parent;
  14.  
  15. - (id)initWithPosition:(CGPoint)pos;
  16. - (int)fscore;
  17.  
  18. @end

正如你所见的,这是一个非常简单的类,其中跟踪保存了以下内容:

  • 瓦块的坐标
  • 分值G(注意,在这里是开始到当前位置的瓦片个数)
  • 分值H(注意,在这里它是当前到结束位置估计的瓦块数量)
  • ShortestPathStep来自哪里
  • 分值F,就是该瓦块的分值(用F + G来计算).

现在我们可以在CatSprite.m最后(在@end下面)写出实现代码:

  1. @implementation ShortestPathStep
  2.  
  3. @synthesize position;
  4. @synthesize gscore;
  5. @synthesize hscore;
  6. @synthesize parent;
  7.  
  8. - (id)initWithPosition:(CGPoint)pos
  9. {
  10. if ((self = [super init])) {
  11. position = pos;
  12. gscore = 0;
  13. hscore = 0;
  14. parent = nil;
  15. }
  16. return self;
  17. }
  18.  
  19. - (NSString *)description
  20. {
  21. return [NSString stringWithFormat:@"%@ pos=[%.0f;%.0f] g=%d h=%d f=%d",[super description],self@H_301_180@.position@H_301_180@.x,self@H_301_180@.position@H_301_180@.y,self@H_301_180@.gscore,self@H_301_180@.hscore,[self fscore]];
  22. }
  23.  
  24. - (BOOL)isEqual:(ShortestPathStep *)other
  25. {
  26. return CGPointEqualToPoint(self@H_301_180@.position,other@H_301_180@.position);
  27. }
  28.  
  29. - (int)fscore
  30. {
  31. return self@H_301_180@.gscore + self@H_301_180@.hscore;
  32. }
  33.  
  34. @end

正如你看到的那样,其内容非常直截了当.我们在这里重新定义了description方法,为的是更容易去调试,并且创建了一个isEqual方法,因为2个ShortestPathStep只有在它们的posititon相同时才相同(比如:它们表示同一个瓦块).

猜你在找的Cocos2d-x相关文章