LoginSignup
6
5

More than 5 years have passed since last update.

cocos2d-js でアニメーションを読み込む関数書いた

Last updated at Posted at 2015-02-17

最近 cocos-2d-js やってて、パラパラアニメを読み込むのが面倒だなと思って書いた。
cc.SpriteFrame の配列作って cc.AnimationCache に追加してくだけ。
enchant.js はこういうの用意してた気がするんだけど cocos2d もじつはあったりするのかなぁ。
(追記: plist っていうのを作ってもらえば SpriteFrame 使ってらくできる模様。けど今エフェクト作ってもらってる形式がパラパラアニメな png なので)

var loadAnimation = function (animation_name, width, height, turn_point, count, delay_time, image_path) {
    var x_count = 0;
    var y_count = 0;
    var frames_array = [];
    for (var i = 1; i < count; i++ ) {
        var current_x = width  * x_count;
        var current_y = height * y_count;

        var frame = cc.SpriteFrame.create(
            image_path,
            cc.rect( current_x, current_y, width, height )
        );
        frames_array.push(frame);

        if ( turn_point == 1 || i % turn_point == 0 ) {
            x_count = 0;
            y_count++;
        }
        else {
            x_count++;
        }
    }

    var animation = cc.Animation.create(frames_array, delay_time);
    cc.AnimationCache.getInstance().addAnimation(animation, animation_name);
};

使うときはこんな感じ

loadAnimation("a", 320, 240, 3, 15, 1/20, "parapara_anime.png");
var anim_cache = cc.AnimationCache.getInstance();
var a = anim_cache.getAnimation("a");
a.setRestoreOriginalFrame(true);
var anim = cc.Animate.create(a);
var anim_sprite = cc.Sprite.create();
anim_sprite.setTextureRect(cc.rect(0, 0, 320, 240));
anim_sprite.setPosition(200, 200);
this.addChild(anim_sprite);

anim_sprite.runAction(cc.RepeatForever.create(anim));
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5