[学习笔记] 用TexturePacker建立动画Animation

前端之家收集整理的这篇文章主要介绍了[学习笔记] 用TexturePacker建立动画Animation前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1,下载sprites 图,但是一般都是合起来一整张的

2,用PS进行切片,并保存


3,用TexturePacker去把上面的图合成两个文件,可以给COCOS2D用


4,把这两文件放进项目里,
1),拖进res文件
2)在resource.js里面加入这两个文件



5,开始用Cocos2D写代码吧,官方代码:
var AnimationLayer = cc.Layer.extend({
    spriteSheet:null,
    runningAction:null,
    sprite:null,
    ctor:function () {
        this._super();
        this.init();
    },

    init:function () {
        this._super();

        // create sprite sheet
        cc.spriteFrameCache.addSpriteFrames(res.runner_plist);
        this.spriteSheet = new cc.SpriteBatchNode(res.runner_png);
        this.addChild(this.spriteSheet);


        // init runningAction
        var animFrames = [];
        for (var i = 0; i < 8; i++) {
            var str = "runner" + i + ".png";
            var frame = cc.spriteFrameCache.getSpriteFrame(str);
            animFrames.push(frame);
        }

        var animation = new cc.Animation(animFrames, 0.1);
        this.runningAction = new cc.RepeatForever(new cc.Animate(animation));
        this.sprite = new cc.Sprite("#runner0.png");
        this.sprite.attr({x:80, y:85});
        this.sprite.runAction(this.runningAction);
        this.spriteSheet.addChild(this.sprite);
    }});

6,按照官方代码写,绝对崩溃
好了,现在重点来了...
因为TexturePacker生成文件是PNG的,所以我一直以为程序里的后缀是和官方代码里一样是用PNG的,
但是每次都是运行到 this . sprite = new cc Sprite ( )(就是 ( "#runner0.png" ); ) 就崩溃. 一直没找到原因,

后来终于发现,原来我打包前的文件名是runner_00. gif, runner_01. gif ... 原来是扩展名用错了 ~~


改完之后就是:
var AnimationLayer = cc.Layer.extend({
spriteSheet: null ,
runningAction: null ,
sprite: null ,
ctor: function (){
this ._super();
this .init();
},
init: function (){
var size = cc.winSize;
cc.spriteFrameCache.addSpriteFrames(res.runner_plist); //ATTENTION addSpriteFrames with a "s"
this .spriteSheet = new cc.SpriteBatchNode(res.runner_png);
this .addChild( this .spriteSheet);
var animFrame= [];
for ( var i = 0; i < 6; i++){
var str = "runner_0" + i + ".gif" ; //<<====
var frame = cc.spriteFrameCache.getSpriteFrame(str);
animFrame.push(frame);
}
var animation = cc.Animation(animFrame,0.1);
this .runningAction = new cc.RepeatForever( new cc.Animate(animation));
this .sprite = new cc.Sprite( "#runner_00.gif" ); //<<=====
this .sprite.attr({
x:size.width / 2,
y:size.height / 2
});
this .sprite.runAction( this .runningAction);
this .spriteSheet.addChild( this .sprite);
}
});

猜你在找的Cocos2d-x相关文章