Skip to content

Instantly share code, notes, and snippets.

@sdabet
Last active December 26, 2015 06:18
Show Gist options
  • Save sdabet/7106488 to your computer and use it in GitHub Desktop.
Save sdabet/7106488 to your computer and use it in GitHub Desktop.
Animation of Renegade sprite with cocos2d-html5 sprite
var MyLayer = cc.Layer.extend({
init:function () {
this._super();
var size = cc.Director.getInstance().getVisibleSize();
this.setMouseEnabled(true);
var player = new Player();
player.setPosition(cc.p(size.width/2, size.height/2));
player.setScale(4);
this.player = player;
this.addChild(player);
var label = cc.LabelTTF.create('CLICK ME!');
label.setPosition(cc.p(size.width/2, size.height/2 + 100));
this.addChild(label);
},
onMouseDown:function (touch) {
this.player.punch();
}
});
var MyScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new MyLayer();
this.addChild(layer);
layer.init();
}
});
var Player = cc.Sprite.extend({
WALK_FRAMES: [
"walk1.png", "walk2.png", "walk3.png", "walk4.png",
"walk5.png", "walk4.png", "walk3.png", "walk2.png"
],
PUNCH_FRAMES: [
"punch1.png", "punch2.png", "punch3.png", "punch2.png", "punch1.png",
"punch5.png", "punch6.png", "punch7.png", "punch6.png", "punch5.png"
],
ctor:function () {
this._super();
// Make sure spritesheet is loaded in frame cache
cc.SpriteFrameCache.getInstance().addSpriteFrames(p_Renegade, s_Renegade);
// Set initial frame
this.initWithSpriteFrameName("walk3.png");
// Auto-start walking animation
this.walk();
},
/**
* Schedule the walking animation in endless loop
*/
walk: function() {
this.runAction(
cc.RepeatForever.create(
this._createAnimation(this.WALK_FRAMES)
)
);
},
/**
* Stop current animation, start punch animation and schedule walking animation
*/
punch: function() {
this.stopAllActions();
this.runAction(cc.Sequence.create(
this._createAnimation(this.PUNCH_FRAMES),
cc.CallFunc.create(this.walk, this)
));
},
/**
* Create animation from an array of frame names
*/
_createAnimation: function(frames) {
var cache = cc.SpriteFrameCache.getInstance();
var animation = cc.Animation.create();
for(var i=0; i<frames.length; i++) {
animation.addSpriteFrame(cache.getSpriteFrame(frames[i]));
}
animation.setDelayPerUnit(0.1);
var action = cc.Animate.create(animation);
return action;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment