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

大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处.
如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;)


首先在CatMazeV3中新建CatSprite类,继承于Sprite.其中CatSprite.h文件如下所示:

#import "CCSprite.h"

@class MainScene;

@interface CatSprite : CCSprite

@property (nonatomic,assign,readonly) NSInteger numBones;

-(id)initWithMainScene:(MainScene*)mainScene;
-(void)moveToward:(CGPoint)targetLocation;
-(void)moveTowardOneTile:(CGPoint)location;

@end

和原代码不同的是我将很多实例变量放到了实现m文件中去,所以感觉清爽了不少.同时原来numBones属性在新的Xcode代码中,也不需要再次重新合成了(synthesize).

再看CatSprite.m文件的内容,先是实例变量声明:

@implementation CatSprite{
    MainScene *_mainScene;
    CCAnimation *_facingForwardAnimation;
    CCAnimation *_facingBackAnimation;
    CCAnimation *_facingLeftAnimation;
    CCAnimation *_facingRightAnimation;
    CCAnimation *_curAnimation;
    CCActionMoveTo *_move;
    CCActionAnimate *_curAnimate;
}

注意原来的CCMoveTo和CCAnimate类现在已经不存在了,遂替换为如上所示新的类.

接下来是一些帮助方法和导出方法,没有什么大的改动:

-(id)initWithMainScene:(MainScene *)mainScene{
    self = [super initWithImageNamed:@"cat_forward_1.png"];
    if (self) {
        _mainScene = mainScene;
        _facingForwardAnimation = [self createCatAnimation:@"forward"];
        _facingBackAnimation = [self createCatAnimation:@"back"];
        _facingLeftAnimation = [self createCatAnimation:@"left"];
        _facingRightAnimation = [self createCatAnimation:@"right"];
    }
    return self;
}

-(void)runAnimation:(CCAnimation*)animation{
    if (_curAnimation == animation) {
        return;
    }

    _curAnimation = animation;
    if (_curAnimate) {
        [self stopAction:_curAnimate];
    }

    _curAnimate = [CCActionRepeatForever actionWithAction:
                   [CCActionAnimate actionWithAnimation:animation]];
    [self runAction:_curAnimate];
}

-(CCAnimation*)createCatAnimation:(NSString*)animType{
    CCAnimation *animation = [CCAnimation animation];
    CCSpriteFrameCache *sfCache = [CCSpriteFrameCache sharedSpriteFrameCache];
    for (int i = 1; i <= 2; ++i) {
        [animation addSpriteFrame:[sfCache spriteFrameByName:[NSString stringWithFormat:
                                                              @"cat_%@_%d.png",animType,i]]];
    }
    animation.delayPerUnit = 0.2;
    return animation;
}

注意原来的-(id)initWithLayer:(HelloWorldLayer *)layer方法名称完全改了,因为Layer在v3.4中整个被丢弃了,大家可以看到我写的新的实现,和原来的差不多.

其他的方法中,只是实例变量名和类名发生的变化.我们将在下一篇看如何尝试转换最复杂的moveToward方法.

上一篇:翻翻git之---实现下拉到底刷新RecycleView InfiniteScroll


下一篇:Cocos2D将v1.0的tileMap游戏转换到v3.4中一例(三)