如何在Cocos2D游戏中实现A*寻路算法(六)
然而,就像你在玩时发现的那样,你将看到一堆的问题:
所以注意到这些有问题的部分,我们逐步将游戏逻辑(输/赢,狗狗们,骨头等等)从第一次实现的旧的逻辑中重新添加回来,让我们接下来修复这些问题. 再次添加游戏逻辑为了修复这些问题,按如下代码替换popStepAndAnimate方法中的内容: - (void)popStepAndAnimate
{
// Check if there is still shortestPath
if (self.shortestPath == nil) {
return;
}
// Game Logic (Win / Lose,dogs,bones,etc...)
CGPoint currentPosition = [_layer tileCoordForPosition:self.position];
if ([_layer isBoneAtTilecoord:currentPosition]) {
[[SimpleAudioEngine sharedEngine] playEffect:@"pickup.wav"];
_numBones++;
[_layer showNumBones:_numBones];
[_layer removeObjectAtTileCoord:currentPosition];
}
else if ([_layer isDogAtTilecoord:currentPosition]) {
if (_numBones == 0) {
[_layer loseGame];
self.shortestPath = nil;
return;
}
else {
_numBones--;
[_layer showNumBones:_numBones];
[_layer removeObjectAtTileCoord:currentPosition];
[[SimpleAudioEngine sharedEngine] playEffect:@"catAttack.wav"];
}
}
else if ([_layer isExitAtTilecoord:currentPosition]) {
[_layer winGame];
self.shortestPath = nil;
return;
}
else {
[[SimpleAudioEngine sharedEngine] playEffect:@"step.wav"];
}
// Check if there remains path steps to go trough
if ([self.shortestPath count] == 0) {
self.shortestPath = nil;
return;
}
// Get the next step to move to
ShortestPathStep *s = [self.shortestPath objectAtIndex:0];
CGPoint futurePosition = s.position;
CGPoint diff = ccpSub(futurePosition,currentPosition);
if (abs(diff.x) > abs(diff.y)) {
if (diff.x > 0) {
[self runAnimation:_facingRightAnimation];
}
else {
[self runAnimation:_facingLeftAnimation];
}
}
else {
if (diff.y > 0) {
[self runAnimation:_facingForwardAnimation];
}
else {
[self runAnimation:_facingBackAnimation];
}
}
// Prepare the action and the callback
id moveAction = [CCMoveTo actionWithDuration:0.4 position:[_layer positionForTileCoord:s.position]];
id moveCallback = [CCCallFunc actionWithTarget:self selector:@selector(popStepAndAnimate)]; // set the method itself as the callback
// Remove the step
[self.shortestPath removeObjectAtIndex:0];
// Play actions
[self runAction:[CCSequence actions:moveAction,moveCallback,nil]];
}
没什么神奇的地方,仅仅是原来代码的一点点重构. 编译运行,你将注意到一切都正常了,除了当前一次移动未结束时再次点击屏幕后猫咪奇怪的行为. 因为这个问题和本课程主题没有真正的关系,我不会详细讲述(其实非常简单)实际的实现,但是如果你在意的话,你可以自己下载最终的 Cat Maze project 去看看到底是如何修复的.(其实原因如原作者所说的很简单,就是动画播放依赖性的问题,大家可以直接看源代码. 猫猪注) 恭喜,你已经在一个简单的Cocos2D游戏中从基础开始实现了A*寻路算法! ;) (本系列还没有完哦,后面还有精彩的内容 ;) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |