以上代码块相当直观 - 但是它分解的有些细致了.
首先,敌人通过传递HelloWorldLayer对象的引用而初始化.在init方法里,少数重要的变量被设置:
- maxHP:定义敌人有多经打(Tough guy,eh?)
- wakingSpeed:定义敌人移动的有多快
- mySprite:存储敌人可视化的表示
- destinationWaypoint:存储下一个路径点的引用.
其中update方法是真正见证奇迹的地方(where the magic happens),它每一帧被调用,并且首先检查自身是否到达了目的路径点,使用的方法是你在前面写过的collisionWithCircle方法.如果到达了,它将向下一个路径点前进 - 除非敌人达到终点或者被玩家摧毁了.
然后它沿着到目的路径点的直线移动精灵,用它自己特定的速度前进.它用接下来的算法达到此目的:
- 计算出一个当前位置到目标位置的向量点,然后使它的长度为1以便于处理(normalized变量).
- 将normalized向量乘以移动速度得到在一帧中移动的距离.累加到当前位置上最后得到新的位置.
最终,draw方法简单的在精灵之上实现一个血条.它后续绘制一个红色背景,然后在它之上覆盖一个表示当前敌人HP的绿色矩形条.
现在Enemy类完成了,你可以把它们显示在屏幕上了!
切换至HelloWorldLayer.m文件,完成如下修改:
//At the top of the file: #import "Enemy.h" //Add the following methods: -(BOOL)loadWave { NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"Waves" ofType:@"plist"]; NSArray * waveData = [NSArray arrayWithContentsOfFile:plistPath]; if(wave >= [waveData count]) { return NO; } NSArray * currentWaveData =[NSArray arrayWithArray:[waveData objectAtIndex:wave]]; for(NSDictionary * enemyData in currentWaveData) { Enemy * enemy = [Enemy nodeWithTheGame:self]; [enemies addObject:enemy]; [enemy schedule:@selector(doActivate) interval:[[enemyData objectForKey:@"spawnTime"]floatValue]]; } wave++; [ui_wave_lbl setString:[NSString stringWithFormat:@"WAVE: %d",wave]]; return YES; } -(void)enemyGotKilled { if ([enemies count]<=0) //If there are no more enemies. { if(![self loadWave]) { NSLog(@"You win!"); [[CCDirector sharedDirector] replaceScene:[CCTransitionSplitCols transitionWithDuration:1 scene:[HelloWorldLayer scene]]]; } } } // Add the following to the end of the init method: // 5 - Add enemies enemies = [[NSMutableArray alloc] init]; [self loadWave]; // 6 - Create wave label ui_wave_lbl = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"WAVE: %d",wave] fntFile:@"font_red_14.fnt"]; [self addChild:ui_wave_lbl z:10]; [ui_wave_lbl setPosition:ccp(400,winSize.height-12)]; [ui_wave_lbl setAnchorPoint:ccp(0,0.5)];
所有这些代码的改变需要一些解释.最重要的部分是loadWave方法;他从Waves.plist文件读取数据.