(译)加入敌人和战斗:如果使用cocos2d制作基于tiled地图的游戏:第三部分
?
免责申明(必读!):本博客提供的所有教程的翻译原稿均来自于互联网,仅供学习交流之用,切勿进行商业传播。同时,转载时不要移除本申明。如产生任何纠纷,均与本博客所有人、发表该翻译稿之人无任何关系。谢谢合作!原文链接地址:http://geekanddad.wordpress.com/2010/06/22/enemies-and-combat-how-to-make-a-tile-based-game-with-cocos2d-part-3/程序截图://in the HelloWorld class-(void)addEnemyAtX:(int)x y:(int)y {CCSprite *enemy = [CCSprite spriteWithFile:@"enemy1.png"];enemy.position = ccp(x, y);[self addChild:enemy];}// in the init method - after creating the player// iterate through objects, finding all enemy spawn points// create an enemy for each oneNSMutableDictionary * spawnPoint;for (spawnPoint in [objects objects]) {if ([[spawnPoint valueForKey:@"Enemy"] intValue] ==1){x = [[spawnPoint valueForKey:@"x"] intValue];y = [[spawnPoint valueForKey:@"y"] intValue];[self addEnemyAtX:x y:y];}}?第一个循环遍历对象列表,判断它是否是一个敌人出现的位置点。如果是,则获得它的x和y坐标值,然后调用addEnemyAtX:Y方法把它们加入到合适的地方去。 这个addEnemyAtX:Y方法非常直白,它仅仅是在传入的X,Y坐标值处创建一个敌人精灵。 如果你编译并运行,你会看到这些敌人出现在你之前在Tiled工具中设定的位置处,很酷吧!
// callback. starts another iteration of enemy movement.- (void) enemyMoveFinished:(id)sender {CCSprite *enemy = (CCSprite *)sender;[self animateEnemy: enemy];}// a method to move the enemy 10 pixels toward the player- (void) animateEnemy:(CCSprite*)enemy{// speed of the enemyccTime actualDuration =0.3;// Create the actionsid actionMove = [CCMoveBy actionWithDuration:actualDurationposition:ccpMult(ccpNormalize(ccpSub(_player.position,enemy.position)), 10)];id actionMoveDone = [CCCallFuncN actionWithTarget:selfselector:@selector(enemyMoveFinished:)];[enemy runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];}// add this at the end of addEnemyAtX:y:// Use our animation method and// start the enemy moving toward the player[self animateEnemy:enemy];?animateEnemy:方法创建两个action。第一个action使之朝敌人移动10个像素,时间为0.3秒。你可以改变这个时间使之移动得更快或者更慢。第二个action将会调用enemyMoveFinished:方法。我们使用CCSequence action来把它们组合起来,这样的话,当敌人停止移动的时候就立马可以执行enemyMoveFinished:方法就可以被调用了。在addEnemyAtX:Y:方法里面,我们调用animateEnemy:方法来使敌人朝着玩家(player)移动。(其实这里是个递归的调用,每次移动10个像素,然后又调用enemyMoveFinished:方法)
//immediately before creating the actions in animateEnemy//rotate to face the playerCGPoint diff = ccpSub(_player.position,enemy.position);float angleRadians = atanf((float)diff.y / (float)diff.x);float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);float cocosAngle =-1* angleDegrees;if (diff.x <0) {cocosAngle +=180;}enemy.rotation = cocosAngle?这个代码计算每次玩家相对于敌人的角度,然后旋转敌人来使之面朝玩家。
// at the top of the file add a forward declaration for HelloWorld,// because our two layers need to reference each other@class HelloWorld;// inside the HelloWorldHud class declarationHelloWorld *_gameLayer;// After the class declaration@property (nonatomic, assign) HelloWorld *gameLayer;// Inside the HelloWorld class declarationint _mode;// After the class declaration@property (nonatomic, assign) int mode;?同时修改HelloWorldScene.m文件
// At the top of the HelloWorldHud implementation@synthesize gameLayer = _gameLayer;// At the top of the HelloWorld implementation@synthesize mode = _mode;// in HelloWorld's init method_mode =0;// in HelloWorld's scene method// after layer.hud = hudhud.gameLayer = layer;?如果想知道在cocos2d里面如何使用按钮,可以参照我翻译的另外一篇教程《在cocos2d里面如何制作按钮:简单按钮、单选按钮和开关按钮》。 在HelloWorldScene.m中添加下面的代码,这段代码定义了一个按钮。
Add the folowing code, which defines a button, to HelloWorldScene.m:// in HelloWorldHud's init method// define the buttonCCMenuItem *on;CCMenuItem *off;on = [[CCMenuItemImage itemFromNormalImage:@"projectile-button-on.png"selectedImage:@"projectile-button-on.png" target:nil selector:nil] retain];off = [[CCMenuItemImage itemFromNormalImage:@"projectile-button-off.png"selectedImage:@"projectile-button-off.png" target:nil selector:nil] retain];CCMenuItemToggle *toggleItem = [CCMenuItemToggle itemWithTarget:selfselector:@selector(projectileButtonTapped:) items:off, on, nil];CCMenu *toggleMenu = [CCMenu menuWithItems:toggleItem, nil];toggleMenu.position = ccp(100, 32);[self addChild:toggleMenu];// in HelloWorldHud//callback for the button//mode 0 = moving mode//mode 1 = ninja star throwing mode- (void)projectileButtonTapped:(id)sender{if (_gameLayer.mode ==1) {_gameLayer.mode =0;} else {_gameLayer.mode =1;}}?编译并运行。这时会在左下角出现一个按钮,并且你可以打开或者关闭之。但是这并不会对游戏造成任何影响。我们的下一步就是增加飞镖的发射。
if (_mode ==0) {// old contents of ccTouchEnded:withEvent:} else {// code to throw ninja stars will go here}??好了,看到上面的else部分的注释了吗:在上面的注释后面添加下面的代码:
// Find where the touch isCGPoint touchLocation = [touch locationInView: [touch view]];touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];touchLocation = [self convertToNodeSpace:touchLocation];// Create a projectile and put it at the player's locationCCSprite *projectile = [CCSprite spriteWithFile:@"Projectile.png"];projectile.position = _player.position;[self addChild:projectile];// Determine where we wish to shoot the projectile toint realX;// Are we shooting to the left or right?CGPoint diff = ccpSub(touchLocation, _player.position);if (diff.x >0){realX = (_tileMap.mapSize.width * _tileMap.tileSize.width) +(projectile.contentSize.width/2);} else {realX =-(_tileMap.mapSize.width * _tileMap.tileSize.width) -(projectile.contentSize.width/2);}float ratio = (float) diff.y / (float) diff.x;int realY = ((realX - projectile.position.x) * ratio) + projectile.position.y;CGPoint realDest = ccp(realX, realY);// Determine the length of how far we're shootingint offRealX = realX - projectile.position.x;int offRealY = realY - projectile.position.y;float length = sqrtf((offRealX*offRealX) + (offRealY*offRealY));float velocity =480/1; // 480pixels/1secfloat realMoveDuration = length/velocity;// Move projectile to actual endpointid actionMoveDone = [CCCallFuncN actionWithTarget:selfselector:@selector(projectileMoveFinished:)];[projectile runAction:[CCSequence actionOne:[CCMoveTo actionWithDuration: realMoveDurationposition: realDest]two: actionMoveDone]];?这段代码会在用户点击屏幕的方向发射飞镖。对于这段代码的完整的细节,可以查看我翻译的另一个文章《如何使用cocos2d来做一个简单的iphone游戏教程(第一部分)》。当然,查看原作者的文章后面的注释会更加清楚明白一些。 projectileMoveFinished:方法会在飞镖移动到屏幕之外的时候移除。这个方法非常关键。一旦我们开始做碰撞检测的时候,我们将要循环遍历所有的飞镖。如果我们不移除飞出屏幕范围之外的飞镖的话,这个存储飞镖的列表将会越来越大,而且游戏将会越来越慢。编译并运行工程,现在,你的忍者可以向敌人投掷飞镖了。
NSMutableArray *_enemies;NSMutableArray *_projectiles;?然后初使化_projectiles数组:
// at the end of the launch projectiles section of ccTouchEnded:withEvent:[_projectiles addObject:projectile];// at the end of projectileMoveFinished:[_projectiles removeObject:sprite];?然后在addEnemyAtX:y方法的结尾添加如下代码:
[_enemies addObject:enemy];?接着,在HelloWorld类中添加如下代码:
- (void)testCollisions:(ccTime)dt {NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init];// iterate through projectilesfor (CCSprite *projectile in _projectiles) {CGRect projectileRect = CGRectMake(projectile.position.x - (projectile.contentSize.width/2),projectile.position.y - (projectile.contentSize.height/2),projectile.contentSize.width,projectile.contentSize.height);NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];// iterate through enemies, see if any intersect with current projectilefor (CCSprite *target in _enemies) {CGRect targetRect = CGRectMake(target.position.x - (target.contentSize.width/2),target.position.y - (target.contentSize.height/2),target.contentSize.width,target.contentSize.height);if (CGRectIntersectsRect(projectileRect, targetRect)) {[targetsToDelete addObject:target];}}// delete all hit enemiesfor (CCSprite *target in targetsToDelete) {[_enemies removeObject:target];[self removeChild:target cleanup:YES];}if (targetsToDelete.count >0) {// add the projectile to the list of ones to remove[projectilesToDelete addObject:projectile];}[targetsToDelete release];}// remove all the projectiles that hit.for (CCSprite *projectile in projectilesToDelete) {[_projectiles removeObject:projectile];[self removeChild:projectile cleanup:YES];}[projectilesToDelete release];}?最后,初始化敌人来飞镖数组,并且调度testCollisions:方法,把这些代码加在HelloWorld类的init方法中。
// you need to put these initializations before you add the enemies,// because addEnemyAtX:y: uses these arrays._enemies = [[NSMutableArray alloc] init];_projectiles = [[NSMutableArray alloc] init];[self schedule:@selector(testCollisions:)];?上面的所有的代码,关于具体是如何工作的,可以在我的博客上查找《如何使用COCOS2D制作一个简单的iphone游戏》教程。当然,原作者的文章注释部分的讨论更加清晰,所以我翻译的教程,也希望大家多讨论啊。代码尽量自己用手敲进去,不要为了省事,alt+c,alt+v,这样不好,真的! 好了,现在可以用飞镖打敌人,而且打中之后它们会消失。现在让我们添加一些逻辑,使得游戏可以胜利或者失败吧!
#import "cocos2d.h"@interface GameOverLayer : CCColorLayer {CCLabel *_label;}@property (nonatomic, retain) CCLabel *label;@end@interface GameOverScene : CCScene {GameOverLayer *_layer;}@property (nonatomic, retain) GameOverLayer *layer;@end?相应地修改GameOverScene.m文件:
#import "GameOverScene.h"#import "HelloWorldScene.h"@implementation GameOverScene@synthesize layer = _layer;- (id)init {if ((self = [super init])) {self.layer = [GameOverLayer node];[self addChild:_layer];}return self;}- (void)dealloc {[_layer release];_layer = nil;[super dealloc];}@end@implementation GameOverLayer@synthesize label = _label;-(id) init{if( (self=[super initWithColor:ccc4(255,255,255,255)] )) {CGSize winSize = [[CCDirector sharedDirector] winSize];self.label = [CCLabel labelWithString:@"" fontName:@"Arial" fontSize:32];_label.color = ccc3(0,0,0);_label.position = ccp(winSize.width/2, winSize.height/2);[self addChild:_label];[self runAction:[CCSequence actions:[CCDelayTime actionWithDuration:3],[CCCallFunc actionWithTarget:self selector:@selector(gameOverDone)],nil]];}return self;}- (void)gameOverDone {[[CCDirector sharedDirector] replaceScene:[HelloWorld scene]];}- (void)dealloc {[_label release];_label = nil;[super dealloc];}@end?GameOverLayer仅仅只是在屏幕中间旋转一个label,然后调度一个transition隔3秒后回到HelloWorld场景中。
// put the number of melons on your map in place of the '2'if (_numCollected ==2) {[self win];}?然后,在HelloWorld类中创建win方法:
- (void) win {GameOverScene *gameOverScene = [GameOverScene node];[gameOverScene.layer.label setString:@"You Win!"];[[CCDirector sharedDirector] replaceScene:gameOverScene];}?不要忘了包含头文件:
#import "GameOverScene.h"?编译并运行,当你吃完所有的西瓜后,就会出现如下画面:
for (CCSprite *target in _enemies) {CGRect targetRect = CGRectMake(target.position.x - (target.contentSize.width/2),target.position.y - (target.contentSize.height/2),target.contentSize.width,target.contentSize.height );if (CGRectContainsPoint(targetRect, _player.position)) {[self lose];}}?这个循环遍历所有的敌人,只要有一个敌人精灵的图片所在的矩形和玩家接触到了,那么游戏就失败了。接下,再创建lose方法:
- (void) lose {GameOverScene *gameOverScene = [GameOverScene node];[gameOverScene.layer.label setString:@"You Lose!"];[[CCDirector sharedDirector] replaceScene:gameOverScene];}?编译并运行,一旦有一个敌人碰到你,你就会看到下面的场景: