Question

I'm trying to create an animated sprite in cocos2d-js, but I don't want to use a spritesheet as I did in my cocos2d-iphone project:

NSMutableArray *animationFrames = [NSMutableArray array];
    int frameCount = 0;
    for(int i = 1; i <= 9; ++i)
    {
    CCSpriteFrame *spriteFrame = [CCSpriteFrame frameWithImageNamed:[NSString stringWithFormat:@"hero-%d.png",i]];
    [animationFrames addObject:spriteFrame];
    }
NSLog(@"cria sprite com frames");
_player = [CCSprite spriteWithSpriteFrame:animationFrames.firstObject];

How can I do this in cocos2d-js? I didn't find the same functions in cocos2d-js documentation.

Was it helpful?

Solution

Maybe following code is a little more complicated as it could be. But it works and loads sprites from files and puts together an animation and uses it in a runAction on a sprite (animFrame is an empty array, "this" is a ccLayer).

var str = "";
for (var i = 1; i < 9; i++) {
    str = "mosquito_fly" + (i < 10 ? ("0" + i) : i) + ".png";
    var texture = cc.textureCache.addImage("res/Murbiks/"+str);
    var spriteFrame = cc.SpriteFrame.create(texture,cc.rect(0,0,96,96));
    animFrames.push(spriteFrame);
}

var animation = cc.Animation.create(animFrames, 0.06+Math.random()*0.01, 10);
var animate = this.animateMostafa = cc.Animate.create(animation);

// Create sprite and set attributes
mostafa = cc.Sprite.create(res.Mostafa_single_png);        
mostafa.attr({
    x: 0,
    y: 0,
    scale: 0.60+Math.random()*0.3,
    rotation: 0
});
this.addChild(mostafa, 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top