Press Key and Play Animation

Hi,

I’m working with Cocos Creator, and trying to set up when player presses key, it will play an animation I’ve set up and saved, please see below:

testrunleftanimation: function(){
var testingrunleft = this.getComopnent(cc.Animation);
this.testingrunleft.play(‘testingrunleftanim’);
},

setInputControl: function () {
var self = this;
// add keyboard event listener
cc.eventManager.addListener({
event: cc.EventListener.KEYBOARD,
// When there is a key being pressed down, judge if it’s the designated directional button and set up acceleration in the corresponding direction
onKeyPressed: function(keyCode, event) {
switch(keyCode) {
case cc.KEY.a:
self.accLeft = true;
self.accRight = false;
this.testrunleftanimation();
break;
case cc.KEY.d:
self.accLeft = false;
self.accRight = true;
break;
}
},

I’ve also added the animation component to the node which is player, and I’ve included the 2 animations in the animclip within the component, and play on load to false. However, when I press it doesn’t play the animation on the player ( character ). What piece am I missing? Any help or insight would be appreciated it…Thanks and God Bless…

Sincerely,

Sunday

addListener requires a second argument - a number or a node to use as event listener’s priority. I suppose it is used for resolving execution order when an event triggers several listeners and you don’t need it yet, but Cocos requires you to specify it anyway :grimacing:

Also this would be something different inside your event listener callback (probably the listener itself, or the event) so you should use variable self you’ve declared

And also you forgot a .node in your first function.

And your setInputControl won’t be called automatically, you understand it, right?

testrunleftanimation: function(){
	var testingrunleft = this.node.getComopnent(cc.Animation);
	testingrunleft.play('testingrunleftanim');
},

setInputControl: function () {
	var self = this;
	// add keyboard event listener
	cc.eventManager.addListener({
	
		event: cc.EventListener.KEYBOARD,
	
// When there is a key being pressed down, judge if it's the designated directional button and set up acceleration in the corresponding direction
		onKeyPressed: function(keyCode, event) {
			switch(keyCode) {
				case cc.KEY.a:
					self.accLeft = true;
					self.accRight = false;
					self.testrunleftanimation();
					break;
				case cc.KEY.d:
					self.accLeft = false;
					self.accRight = true;
					break;
			}
		}

	}, this.node)
},

onLoad: function() {
	this.setInputControl();
},

I highly recommend you to read something about variable scopes because you keep confusing vars and table values of this

Hi,

Thanks for the help, much appreciation, yes indeed to variable scopes, var table values, may I ask, what tutorial would you recommend for learning such concepts? Thanks again for the insights, and God Bless…

Sincerely,

Sunday