(NO.00004)iOS实现打砖块游戏(十四):3球道具的实现 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

   

    反弹棒变化道具实现前面已经介绍过了,我们下面可以在小球上做些文章,实现一个道具可以变出更多的小球出来.

    我们称之为3球道具:当反弹棒碰到该道具时,小球变为3枚,接下来你尽可能保持这些小球不掉落,这样你可以得到比1个球时更多地分数.

    打开Xcode,在Star.m中的spawnStar方法条件中加入新的分支:

<code bash="" class="hljs">case brkColorPurple:            star = [Star starWithType:starTypeThreeBalls];            break;</code>

    因为在Star.m的方法中需要知道当前场景中小球的状态,所以先在GameScene.h接口中添加2个新的方法:

<code class="hljs" erlang="">-(void)addBall:(CCSprite*)ball;-(NSInteger)currentBallsCount;</code>

    回到GameScene.m中,扩展代码增加一个新的实例变量,用来表示当前所有小球:

<code class="hljs" perl="">NSMutableArray *_balls;</code>

    接着我们实现上面新加的2个方法:

<code class="hljs" scss="">//在GameScene中添加小球,小球的位置必须已经被正确设置-(void)addBall:(CCSprite*)ball{    @synchronized(self){        [_physicsWorld addChild:ball];        [_balls addObject:ball];    }}-(NSInteger)currentBallsCount{    @synchronized(self){        return _balls.count;    }}</code>

    注意方法中都设置了同步,因为读取时可能发生修改,如果不加同步,app可能会发生crash!

    再回到Star.m中,我们添加关键的道具功能方法doThreeBalls:

<code class="hljs" lua="">+(void)doThreeBalls:(CGPoint)ballLocation{    GameScene *gameScene = [GameScene sharedGameScene];    if ([gameScene currentBallsCount] != 1) {        return;    }    CCSprite *ball2 = (CCSprite*)[CCBReader load:@Elements/Ball];    ball2.position = ballLocation;    [gameScene addBall:ball2];    CCSprite *ball3 = (CCSprite*)[CCBReader load:@Elements/Ball];    ball3.position = ballLocation;    [gameScene addBall:ball3];}</code>

    代码首先检查当前场景中有多少个小球,如果多余1个则直接返回,就是说该道具只能在只有1枚小球时发挥作用.

    接着创建另外2个小球,通过之前定义的addBall方法,把它们添加到场景中去.

    最后在GameScene.m的碰撞处理中增加新选择分支:

<code class="hljs" ruby="">case starTypeThreeBalls:            @synchronized(self){                if ([self currentBallsCount] >= 1) {                    [self scheduleBlock:^(CCTimer *timer){                        [Star doThreeBalls:((CCSprite*)_balls[0]).position];                    } delay:0];                }            }            break;</code>

    现在编译连接app,运行效果如下:

   

最新文章