Cocos2D将v1.0的tileMap游戏转换到v3.4中一例(五)

时间:2021-11-10 19:05:13

大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处.

如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;)


为了暂时不影响原来的cat移动方法,我们在CatSprite.m中新建一个移动方法,内容如下,其中考虑了与地图的碰撞情况:

-(void)moveTowardOneTile:(CGPoint)location{
    CGPoint diff = ccpSub(location, self.position);
    CGPoint desiredTileCoord = [_mainScene tileCoordForPosition:self.position];

    if (fabsf(diff.x) > fabsf(diff.y)) {
        if (diff.x > 0) {
            desiredTileCoord.x += 1;
            [self runAnimation:_facingRightAnimation];
        } else {
            desiredTileCoord.x -= 1;
            [self runAnimation:_facingLeftAnimation];
        }
    } else {
        if (diff.y > 0) {
            desiredTileCoord.y -= 1;
            [self runAnimation:_facingBackAnimation];
        } else {
            desiredTileCoord.y += 1;
            [self runAnimation:_facingForwardAnimation];
        }
    }

    if ([_mainScene isWallAtTileCoord:desiredTileCoord]) {
        //[[SimpleAudioEngine sharedEngine] playEffect:@"hitWall.wav"];
    } else {
        self.position = [_mainScene positionForTileCoord:desiredTileCoord];

        if ([_mainScene isBoneAtTileCoord:desiredTileCoord]) {
            //[[SimpleAudioEngine sharedEngine] playEffect:@"pickup.wav"];
            _numBones++;
            //[_mainScene showNumBones:_numBones];
            [_mainScene removeObjectAtTileCoord:desiredTileCoord];
        } else if ([_mainScene isDogAtTileCoord:desiredTileCoord]) {
            if (_numBones == 0) {
                //[_layer loseGame];
            } else {
                _numBones--;
                //[_layer showNumBones:_numBones];
                [_mainScene removeObjectAtTileCoord:desiredTileCoord];
                //[[SimpleAudioEngine sharedEngine] playEffect:@"catAttack.wav"];
            }
        } else if ([_mainScene isExitAtTileCoord:desiredTileCoord]) {
            //[_layer winGame];
        } else {
            //[[SimpleAudioEngine sharedEngine] playEffect:@"step.wav"];
        }
    }
}

注意代码中将原代码的与音效相关的部分统统省略,因为本猫的mini在调试声音的App时有点问题,大家如果加上音效代码也是没问题的,请随意 ;)

回到MainScene.m中将touchBegan方法中对cat移动的代码改为新的方法:

[_cat moveTowardOneTile:location];

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

Cocos2D将v1.0的tileMap游戏转换到v3.4中一例(五)

现在我们可爱的鼠大盗已经不能穿墙行走了,下一篇中我们将原来所有的游戏逻辑全部补全(除去音乐和音效),下篇见 ;)