Cocos2D iOS之旅:如何写一个敲地鼠游戏(十一):完善游戏逻辑
好了,现在我们用userData标志来确定是否可以点击精灵,我们可以最后添加如下敲击反馈代码了: -(void) registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:kCCMenuTouchPriority swallowsTouches:NO];
}
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
for (CCSprite *mole in moles) {
if (mole.userData == FALSE) continue;
if (CGRectContainsPoint(mole.boundingBox,touchLocation)) {
mole.userData = FALSE;
score+= 10;
[mole stopAllActions];
CCAnimate *hit = [CCAnimate actionWithAnimation:hitAnim restoreOriginalFrame:NO];
CCMoveBy *moveDown = [CCMoveBy actionWithDuration:0.2 position:ccp(0,-mole.contentSize.height)];
CCEaseInOut *easeMoveDown = [CCEaseInOut actionWithAction:moveDown rate:3.0];
[mole runAction:[CCSequence actions:hit,easeMoveDown,nil]];
}
}
return TRUE;
}
registerWithTouchDispatcher方法为每一次触摸设置触摸回调方法ccTouchBegan.更详细内容,你可以在 How To Make Tile Based Game with Cocos2D Tutorial中学习到. 在ccToucheBegan方法中将坐标转换为相对于该层,然后遍历每一个只地鼠.如果地鼠是不可敲击的(usrData是false)它将跳到下一只地鼠上.否则它使用CGRectContainsPoint函数检查触摸点是否在地鼠的范围之内. 如果地鼠被敲击,设置其不可再被敲击,然后增加分数.接着停止任何运行着的动作,播放”被敲时”的动画,并且立即将地鼠移动到洞里. 在最后一步 — 增加一些代码更新分数并且在tryPopMole中检查关卡是否完成的标志 : if (gameOver) return;
[label setString:[NSString stringWithFormat:@"Score: %d",score]];
if (totalSpawns >= 50) {
CGSize winSize = [CCDirector sharedDirector].winSize;
CCLabelTTF *goLabel = [CCLabelTTF labelWithString:@"Level Complete!" fontName:@"Verdana" fontSize:[self convertFontSize:48.0]];
goLabel.position = ccp(winSize.width/2,winSize.height/2);
goLabel.scale = 0.1;
[self addChild:goLabel z:10];
[goLabel runAction:[CCScaleTo actionWithDuration:0.5 scale:1.0]];
gameOver = true;
return;
}
That’s it!编译运行你的代码,你应该看到地鼠被敲同时分数被更新!你最高能得多少分呢? 添加音效像往常一样,让我们添加一些有趣的音效.下载 sound effects,这是我用GarageBand和Audacity制作的,解压然后拖拽到你的Resources文件夹中.确保”Copy items into destination group’s folder”被选中,然后点击添加. 如下修改HelloWorldScene.m文件: // Add to top of file
#import "SimpleAudioEngine.h"
// Add at the bottom of your init method
[[SimpleAudioEngine sharedEngine] preloadEffect:@"laugh.caf"];
[[SimpleAudioEngine sharedEngine] preloadEffect:@"ow.caf"];
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"whack.caf" loop:YES];
// Add at bottom of setTappable
[[SimpleAudioEngine sharedEngine] playEffect:@"laugh.caf"];
// Add inside ccTouchBegan,inside the CGRectContainsPoint case
[[SimpleAudioEngine sharedEngine] playEffect:@"ow.caf"];
编译运行你的代码,享受这优美的曲调吧! (下面是本猫编译运行的app效果: 接下来我们该做神马呢?这里有一个 sample project 包含了迄今为止所有的内容 这就是本系列博文的全部内容(至少对于现在来说),但只要你想,为什么不自己做些其他修改呢?我觉得你可以完善的更好! (本系列完) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |