本文是“使用Cocos2D 3.x开发横版动作游戏”系列教程的第二篇,同时也是最后一篇。是对How To Make A Side-Scrolling Beat Em Up Game Like Scott Pilgrim with Cocos2D – Part 2的翻译,加上个人理解而成。最重要的是将文中所有代码转换为Cocos2D 3.x版本。众所周知,3.x与2.x的区别非常之大,在触摸机制、渲染机制等方面都与之前版本有了本质的区别。这里将本人摸索的结果加上,供大家参考。
在上一篇教程中,我们已经加载了TiledMap,创建了Hero,并且实现了一个简单地虚拟摇杆。但是我们的虚拟摇杆还无法投入到使用中,无法移动我们的Hero,并且我们并没有加入敌人,这实在不算是一个横版动作游戏。
本篇教程中我将带着大家完成这个游戏,包括实现人物的移动,地图的滚动,碰撞检测、创建敌人、人工智能以及音乐播放。
首先,你要有我们上一篇教程最后写好的项目,也就是我们的第一部分的代码。如果你还没有,你可以从这里下载。
接下来让我们开始吧!
//walk action NSMutableArray *walkFrames = [NSMutableArray arrayWithCapacity:8]; for (int i = 0; i < 8; i++) { CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"hero_walk_%02d.png", i]]; [walkFrames addObject:frame]; } CCAnimation *walkAnimation = [CCAnimation animationWithSpriteFrames:walkFrames delay:1.0 / 12.0f]; self.walkAction = [CCActionRepeatForever actionWithAction:[CCActionAnimate actionWithAnimation:walkAnimation]];
- (void)walkWithDirection:(CGPoint)direction { if (self.state == kActionStateIdle) { [self stopAllActions]; [self runAction:self.walkAction]; self.state = kActionStateWalk; } if (self.state == kActionStateWalk) { self.velocity = ccp(direction.x * self.walkSpeed, direction.y * self.walkSpeed); if (self.velocity.x >= 0) { self.scaleX = 1.0; } else { self.scaleX = -1.0; } } }
#pragma mark - SimpleDPadDelegate - (void)simpleDPad:(SimpleDPad *)dPad didChangeDirectionTo:(CGPoint)direction { [self.hero walkWithDirection:direction]; } - (void)simpleDPad:(SimpleDPad *)dPad isHoldingDirection:(CGPoint)direction { [self.hero walkWithDirection:direction]; } - (void)simpleDPadTouchEnded:(SimpleDPad *)dPad { if (self.hero.state == kActionStateWalk) { [self.hero idle]; } }
#pragma mark - Schedule - (void)update:(CCTime)delta { if (self.state == kActionStateWalk) { self.desiredPosition = ccpAdd(self.position, ccpMult(self.velocity, delta)); } }
注意:在3.x中,我们不需要显示调用[self scheduleUpdate];了,当我们重写了CCNode的update:方法时,Cocos2D会自动为我们每帧调用这里的方法。因此,此时我们实现了Hero的“期望”位置更新逻辑之后,就不需要在GameLayer的update中调用该方法了(当然,调用了也没有事,而且可能逻辑更清晰一些),这是与原教程的另一个不同之处。 |
#pragma mark - Schedule - (void)update:(CCTime)delta { [self updatePosition]; } - (void)updatePosition { float posX = MIN(self.tileMap.tileSize.width * self.tileMap.mapSize.width - self.hero.centerToSides, MAX(self.hero.centerToSides, self.hero.desiredPosition.x)); float posY = MIN(ROAD_MAP_SIZE * self.tileMap.tileSize.height + self.hero.centerToBottom, MAX(self.hero.centerToBottom, self.hero.desiredPosition.y)); self.hero.position = ccp(posX, posY); } #pragma mark - EndGame - (void)dealloc { [self unscheduleAllSelectors]; }
#define ROAD_MAP_SIZE 3在这段代码中,你设置了一个定时器,不断刷新主角的位置。主角的位置并不是简单地设置为“期望”位置,因为主角不能跑到地图之外。拿x方向来说,这里用了centerToSides作为最小值,地图横线距离减去centerToSides作为最大值,规定主角在这个范围之间移动。Cocos2D中有一个宏ccClamp可以实现同样地功能。
- (void)updateViewPointCenter:(CGPoint)point { float x = MAX(VISIBLE_SIZE.width / 2, point.x); float y = MAX(VISIBLE_SIZE.height / 2, point.y); x = MIN(x, (self.tileMap.mapSize.width * self.tileMap.tileSize.width) - VISIBLE_SIZE.width / 2); y = MIN(y, (self.tileMap.mapSize.height * self.tileMap.tileSize.height) - VISIBLE_SIZE.height / 2); CGPoint actualPoint = ccp(x, y); CGPoint centerPoint = ccp(VISIBLE_SIZE.width / 2, VISIBLE_SIZE.height / 2); CGPoint viewPoint = ccpSub(centerPoint, actualPoint); self.position = viewPoint; }
//在update:方法中添加下面这一行 [self updateViewPointCenter:self.hero.position];这个方法比较三个点的x、y的大小:传入点,当前视中心点,到达最右边缘后视中心点。初始状态下“当前视中心点”也可以看做“到达最左边缘后视中心点”。也就是说,当传入点在左右边缘范围内移动时,视中心点随着该点的移动而不断切换。而到达两侧边缘后,视中心点固定不变。这样就达到了随着传入点(主角的位置)移动视图的效果。另外,我们这里与传统纵版射击类游戏不同的是,很多纵版射击类游戏通过两张背景拼接、移动Sprite来达到移动背景的效果。而这里移动的却是layer,也就是self.position。
- (id)init { self = [super initWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"robot_idle_00.png"]]; if (self) { //idle NSMutableArray *idleFrame = [NSMutableArray arrayWithCapacity:5]; for (int i = 0; i < 5; i++) { CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"robot_idle_%02d.png", i]]; [idleFrame addObject:frame]; } CCAnimation *idleAnimation = [CCAnimation animationWithSpriteFrames:idleFrame delay:1.0 / 12.0f]; self.idleAction = [CCActionRepeatForever actionWithAction:[CCActionAnimate actionWithAnimation:idleAnimation]]; //attack NSMutableArray *attackFrame = [NSMutableArray arrayWithCapacity:5]; for (int i = 0; i < 5; i++) { CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"robot_attack_%02d.png", i]]; [attackFrame addObject:frame]; } CCAnimation *attackAnimation = [CCAnimation animationWithSpriteFrames:attackFrame delay:1.0 / 24.0f]; self.attackAction = [CCActionSequence actionOne:[CCActionAnimate actionWithAnimation:attackAnimation] two:[CCActionCallFunc actionWithTarget:self selector:@selector(idle)]]; //walk NSMutableArray *walkFrame = [NSMutableArray arrayWithCapacity:6]; for (int i = 0; i < 6; i++) { CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"robot_walk_%02d.png", i]]; [walkFrame addObject:frame]; } CCAnimation *walkAnimation = [CCAnimation animationWithSpriteFrames:walkFrame delay:1.0 / 12.0f]; self.walkAction = [CCActionRepeatForever actionWithAction:[CCActionAnimate actionWithAnimation:walkAnimation]]; self.walkSpeed = 80; self.centerToBottom = 39.0f; self.centerToSides = 29.0f; self.hitPoints = 100; self.damage = 10; } return self; }
@property (strong, nonatomic) NSMutableArray *robots;
- (void)initRobots { int robotsNumber = 50; self.robots = [NSMutableArray arrayWithCapacity:robotsNumber]; Robot *temp = [Robot node]; int minX = VISIBLE_SIZE.width + temp.centerToSides; int minY = temp.centerToBottom; int maxX = self.tileMap.mapSize.width * self.tileMap.tileSize.width - temp.centerToSides; int maxY = ROAD_MAP_SIZE * self.tileMap.tileSize.height + temp.centerToBottom; for (int i = 0; i < robotsNumber; i++) { Robot *robot = [Robot node]; [self addChild:robot z:-5]; [self.robots addObject:robot]; [robot setPosition:ccp(RANDOM_RANGE(minX, maxX), RANDOM_RANGE(minY, maxY))]; robot.desiredPosition = robot.position; robot.scaleX = -1; [robot idle]; } }
- (void)reorderActors { for (CCNode *sprite in self.children) { if ([sprite isKindOfClass:[ActionSprite class]]) { [self reorderChild:sprite z:self.tileMap.mapSize.height * self.tileMap.tileSize.height - sprite.position.y]; } } }
#import "CCNode_Private.h"
//struct typedef struct BoundingBox { CGRect actual; CGRect original; } BoundingBox;这个结构体是干什么用的呢?它定义了两个CGRect类型的变量。original用来表示精灵的初始化状态下的坐标与大小,由于精灵(主角和Robot)是会动的,所以我们需要一个actual来记录某一时刻精灵的实际位置与大小(大小往往不变,变的是方向,后文会有详述)。
//boundingBox @property (assign, nonatomic) BoundingBox hitBox; @property (assign, nonatomic) BoundingBox attackBox; //create bounding box - (BoundingBox)createBoundingBoxWithOrigin:(CGPoint)origin andSize:(CGSize)size;
#pragma mark - BoundingBox - (BoundingBox)createBoundingBoxWithOrigin:(CGPoint)origin andSize:(CGSize)size { BoundingBox box; box.original.origin = origin; box.original.size = size; box.actual.origin = ccpAdd(self.position, ccp(origin.x, origin.y)); box.actual.size = size; return box; } - (void)transformBoundingBox { //to consider the direction of sprite, we should use scale //onle _xxx could be assinged,self.xxx is not assingable _hitBox.actual.origin = ccpAdd(self.position, ccp(self.hitBox.original.origin.x * self.scaleX, self.hitBox.original.origin.y * self.scaleY)); _hitBox.actual.size = CGSizeMake(self.hitBox.original.size.width * self.scaleX, self.hitBox.original.size.height * self.scaleY); _attackBox.actual.origin = ccpAdd(self.position, ccp(self.attackBox.original.origin.x * self.scaleX, self.attackBox.original.origin.y * self.scaleY)); _attackBox.actual.size = CGSizeMake(self.attackBox.original.size.width * self.scaleX, self.attackBox.original.size.height * self.scaleY); } #pragma mark - Setter - (void)setPosition:(CGPoint)position { [super setPosition:position]; [self transformBoundingBox]; }
//based on center of sprite self.hitBox = [self createBoundingBoxWithOrigin:ccp(-self.centerToSides, -self.centerToBottom) andSize:CGSizeMake(self.centerToSides * 2, self.centerToBottom * 2)]; self.attackBox = [self createBoundingBoxWithOrigin:ccp(self.centerToSides, -10) andSize:CGSizeMake(20, 20)];
//based on center of sprite self.hitBox = [self createBoundingBoxWithOrigin:ccp(-self.centerToSides, -self.centerToBottom) andSize:CGSizeMake(self.centerToSides * 2, self.centerToBottom * 2)]; self.attackBox = [self createBoundingBoxWithOrigin:ccp(self.centerToSides, -5) andSize:CGSizeMake(25, 20)];
- (void)hurtWithDamage:(CGFloat)damage { if (self.state != kActionStateKnockedOut) { [self stopAllActions]; [self runAction:self.hurtAction]; self.state = kActionStateHurt; self.hitPoints -= damage; if (self.hitPoints <= 0) { [self knockOut]; } } } - (void)knockOut { [self stopAllActions]; [self runAction:self.knockedOutAction]; self.hitPoints = 0; self.state = kActionStateKnockedOut; }
//hurt action NSMutableArray *hurtFrames = [NSMutableArray arrayWithCapacity:3]; for (int i = 0; i < 3; i++) { CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"hero_hurt_%02d.png", i]]; [hurtFrames addObject:frame]; } CCAnimation *hurtAnimation = [CCAnimation animationWithSpriteFrames:hurtFrames delay:1.0 / 12.0f]; self.hurtAction = [CCActionSequence actionOne:[CCActionAnimate actionWithAnimation:hurtAnimation] two:[CCActionCallFunc actionWithTarget:self selector:@selector(idle)]]; //knock out action NSMutableArray *knockOutFrames = [NSMutableArray arrayWithCapacity:5]; for (int i = 0; i < 5; i++) { CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"hero_knockout_%02d.png", i]]; [knockOutFrames addObject:frame]; } CCAnimation *knockOutAnimation = [CCAnimation animationWithSpriteFrames:knockOutFrames delay:1.0 / 12.0f]; self.knockedOutAction = [CCActionSequence actionOne:[CCActionAnimate actionWithAnimation:knockOutAnimation] two:[CCActionBlink actionWithDuration:2.0f blinks:10.0f]];类似地,打开Robot.m,在同样地位置添加:
//hurt action NSMutableArray *hurtFrames = [NSMutableArray arrayWithCapacity:3]; for (int i = 0; i < 3; i++) { CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"robot_hurt_%02d.png", i]]; [hurtFrames addObject:frame]; } CCAnimation *hurtAnimation = [CCAnimation animationWithSpriteFrames:hurtFrames delay:1.0 / 12.0f]; self.hurtAction = [CCActionSequence actionOne:[CCActionAnimate actionWithAnimation:hurtAnimation] two:[CCActionCallFunc actionWithTarget:self selector:@selector(idle)]]; //knock out action NSMutableArray *knockOutFrames = [NSMutableArray arrayWithCapacity:5]; for (int i = 0; i < 5; i++) { CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"robot_knockout_%02d.png", i]]; [knockOutFrames addObject:frame]; } CCAnimation *knockOutAnimation = [CCAnimation animationWithSpriteFrames:knockOutFrames delay:1.0 / 12.0f]; self.knockedOutAction = [CCActionSequence actionOne:[CCActionAnimate actionWithAnimation:knockOutAnimation] two:[CCActionBlink actionWithDuration:2.0f blinks:10.0f]];
//添加到touchBegan的[self.hero attack]后 //collision detection if (self.hero.state == kActionStateAttack) { for (Robot *robot in self.robots) { if (robot.state != kActionStateKnockedOut) { if (fabsf(robot.position.y - self.hero.position.y) < 10) { if (CGRectIntersectsRect(robot.hitBox.actual, self.hero.attackBox.actual)) { [robot hurtWithDamage:self.hero.damage]; } } } } }
@property (assign, nonatomic) double nextDecisionTime;在Robot.m中的init方法中进行初始化:
self.nextDecisionTime = 0;见名知意,这个属性表示下一次决策时间。
<span style="font-size:14px;">- (void)updateRobots:(CCTime)delta { int alive = 0; int randomChoice = 0; float distanceSQ = 0; for (Robot *robot in self.robots) { [robot update:delta]; if (robot.state != kActionStateKnockedOut) { alive++; if (CURRENT_TIME > robot.nextDecisionTime) { distanceSQ = ccpDistanceSQ(robot.position, self.hero.position); if (distanceSQ <= 50 * 50) { robot.nextDecisionTime = CURRENT_TIME + FLOAT_RANDOM_RANGE(0.1, 0.5); randomChoice = RANDOM_RANGE(0, 1); if (randomChoice == 0) { if (self.position.x >= robot.position.x) { robot.scaleX = 1.0; } else { robot.scaleX = -1.0; } //attack and collision detection [robot attack]; if (robot.state == kActionStateAttack) { if (self.hero.state != kActionStateKnockedOut) { if (fabsf(robot.position.y - self.hero.position.y) < 10) { if (CGRectIntersectsRect(robot.attackBox.actual, self.hero.hitBox.actual)) { [self.hero hurtWithDamage:robot.damage]; } } } } } } else { [robot idle]; } } else if (distanceSQ <= VISIBLE_SIZE.width * VISIBLE_SIZE.width) { robot.nextDecisionTime = CURRENT_TIME + FLOAT_RANDOM_RANGE(0.5, 1.0); randomChoice = RANDOM_RANGE(0, 2); if (randomChoice == 0) { //move CGPoint direction = ccpNormalize(ccpSub(self.hero.position, robot.position)); [robot walkWithDirection:direction]; } else { [robot idle]; } } //distance } //if (CURRENT_TIME > robot.nextDecisionTime) } //if (robot.state != kActionStateKnockedOut) } //foreach }</span>
[self updateRobots:delta];
//在updatePosition方法中添加 for (Robot *robot in self.robots) { float robotPosX = MIN(self.tileMap.tileSize.width * self.tileMap.mapSize.width - robot.centerToSides, MAX(robot.centerToSides, robot.desiredPosition.x)); float robotPosY = MIN(ROAD_MAP_SIZE * self.tileMap.tileSize.height + robot.centerToBottom, MAX(robot.centerToBottom, robot.desiredPosition.y)); robot.position = ccp(robotPosX, robotPosY); }
- (void)endGameWithResult:(GameResult)result { NSString *label = nil; if (result == kGameResultLost) { label = @"Game Over"; } else if (result == kGameResultWin) { label = @"You Win!"; } CCButton *restartBtn = [CCButton buttonWithTitle:label fontName:@"Arial" fontSize:30]; [restartBtn setPosition:CENTER]; [restartBtn setTarget:self selector:@selector(restartGame)]; restartBtn.name = @"restart"; [self.scene addChild:restartBtn z:500]; } - (void)restartGame { CCTransition *trans = [CCTransition transitionFadeWithDuration:0.4f]; trans.outgoingSceneAnimated = YES; trans.incomingSceneAnimated = YES; [[CCDirector sharedDirector] replaceScene:[GameScene node] withTransition:trans]; }其中GameResult是自己定义的枚举变量,其值也都在if-else块中体现出来了。
//添加到updateRobots方法的最下端,最外层循环之外 //check game win if (alive == 0 && [self getChildByName:@"restart" recursively:YES] == nil) { [self endGameWithResult:kGameResultWin]; }
//添加到[self.hero hurtWithDamage:robot.damage];之后 //check game over if (self.hero.state == kActionStateKnockedOut && [self getChildByName:@"restart" recursively:YES] == nil) { [self endGameWithResult:kGameResultLost]; }和这群机器人玩得愉快!
注意:3.x中Cocos2D已经不用SimpleAudioEngine来处理音乐了,而是采用OpenAL,对应的类名为OALSimpleAudio,对于我们使用来说大同小异。同样的单例、同样的prepare,同样的play…… |
- (void)initMusics { [[OALSimpleAudio sharedInstance] preloadBg:@"latin_industries.aifc"]; [[OALSimpleAudio sharedInstance] playBg:@"latin_industries.aifc" loop:YES]; OALSimpleAudio *audio = [OALSimpleAudio sharedInstance]; [audio preloadEffect:@"pd_botdeath.caf"]; [audio preloadEffect:@"pd_herodeath.caf"]; [audio preloadEffect:@"pd_hit0.caf"]; [audio preloadEffect:@"pd_hit1.caf"]; }
int randomSound = RANDOM_RANGE(0, 1); [[OALSimpleAudio sharedInstance] playEffect:[NSString stringWithFormat:@"pd_hit%d.caf", randomSound]];
- (void)knockOut { [super knockOut]; [[OALSimpleAudio sharedInstance] playEffect:@"pd_herodeath.caf"]; }
- (void)knockOut { [super knockOut]; [[OALSimpleAudio sharedInstance] playEffect:@"pd_botdeath.caf"]; }