您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 實作炸彈人遊戲(九):遊戲主角(二)

編輯:iOS 開發綜合

大熊貓豬·侯佩原創或翻譯作品。歡迎轉載,轉載請注明出處。如果覺得寫得不好請多提意見,如果覺得不錯請多多支持點贊。謝謝!hopy ;)


上一篇介紹了主角的初始化方法,本篇接著實作主角的其他方法。先來看 runAnimation,我們用它來播放主角的動畫:

 -(void)runAnimation:(CCAnimation*)animation{ if (_curAnimation == animation) { return; } _curAnimation = animation; if (_curAnimate) { [self stopAction:_curAnimate]; } _curAnimate = [CCActionRepeatForever actionWithAction: [CCActionAnimate actionWithAnimation:animation]]; [self runAction:_curAnimate]; }

程式碼首先檢查即將播放的動畫是否與目前播放的相同,若相同則直接退出;接著若目前有正在播放的動畫動作,就先將它停止;然後為待播放的動畫建立一個永久循環的動作並運行它。

接下來是 A* 尋路移動方法,程式碼較長,這裡不逐一細說,所需的觀念在前兩個系列的博文中已完整涵蓋:

 //使用A*尋路算法移動至目標坐標 -(void)moveTowardByAStar:(CGPoint)targetLocation{ if (_currentStepAction) { _pendingMove = [NSValue valueWithCGPoint:targetLocation]; return; } CGPoint fromTileCoord = [_mainScene tileCoordForPosition:self.position]; CGPoint toTileCoord = [_mainScene tileCoordForPosition:targetLocation]; if (CGPointEqualToPoint(fromTileCoord, toTileCoord)) { return; } if (![_mainScene isWalkableTile:toTileCoord forRole:self]) { return; } _spOpenSteps = [NSMutableArray array]; _spClosedSteps = [NSMutableArray array]; _shortestPath = nil; [StarA insertStep:[[ShortestPathStep alloc] initWithPosition:fromTileCoord] toOpenList:_spOpenSteps]; do{ ShortestPathStep *currentStep = _spOpenSteps[0]; [_spClosedSteps addObject:currentStep]; [_spOpenSteps removeObjectAtIndex:0]; if (CGPointEqualToPoint(currentStep.position, toTileCoord)) { //如果已經找到最短路徑則完成該最短路徑的移動動作 [self constructPathAndStartAnimationFromStep:currentStep]; _spOpenSteps = nil; _spClosedSteps = nil; break; } NSArray *adjSteps = [_mainScene walkableAdjacentTilesCoordDiagonallyForTileCoord: currentStep.position forRole:self]; for (NSValue *v in adjSteps) { ShortestPathStep *step = [[ShortestPathStep alloc]initWithPosition:[v CGPointValue]]; if ([_spClosedSteps containsObject:step]) { continue; } int moveCost = [StarA costToMoveDiagonallyFromStep:currentStep toAdjacentStep:step]; NSUInteger index = [_spOpenSteps indexOfObject:step]; if (index == NSNotFound) { step.parent = currentStep; step.gScore = currentStep.gScore + moveCost; step.hScore = [StarA computeHScoreFromCoord:step.position toCoord:toTileCoord]; [StarA insertStep:step toOpenList:_spOpenSteps]; }else{//已經存在於開放列表 step = _spOpenSteps[index]; if ((currentStep.gScore + moveCost) < step.gScore) { step.gScore = currentStep.gScore + moveCost; step.parent = currentStep; [_spOpenSteps removeObjectAtIndex:index]; [StarA insertStep:step toOpenList:_spOpenSteps]; } } } }while (_spOpenSteps.count > 0); }

要補充的是,由於我也是才開始撰寫這類程式碼,一開始對類別元素的掌握還不夠熟練。按理說這個方法是所有遊戲角色都需要的,應該放進它們的父類別裡。的確如此——我在另一款 RPG 遊戲《熊貓之魂》中正是這麼做的,之後有機會再細談。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved