Here is the code (I am applying the script to the current entity (this.entity)):
var AnimationHandler = pc.createScript('animationHandler');
// initialize code called once per entity
AnimationHandler.prototype.initialize = function() {
};
// update code called every frame
AnimationHandler.prototype.update = function(dt) {
if (this.app.keyboard.isPressed(pc.KEY_LEFT)) {
this.entity.sprite.play('moving');
}
if (this.app.keyboard.isPressed(pc.KEY_RIGHT)) {
this.entity.sprite.play('moving');
}
if (this.app.keyboard.isPressed(pc.KEY_DOWN)) {
this.entity.sprite.play('moving');
}
if (this.app.keyboard.isPressed(pc.KEY_UP)) {
this.entity.sprite.play('moving');
}
//stop the moving sprite clip, switch to idle
if (this.app.keyboard.wasPressed(pc.KEY_RIGHT)) {
this.entity.sprite.stop('moving');
}
//another method for the code above
AnimationHandler.prototype.onKeyUp = function (event) {
// Check event.key to detect which key has been pressed
if (event.key === pc.KEY_LEFT) {
this.entity.sprite.stop('moving');
this.entity.sprite.play('idle');
}
};
AnimationHandler.prototype.onKeyUp = function (event) {
// Check event.key to detect which key has been pressed
if (event.key === pc.KEY_RIGHT) {
this.entity.sprite.stop('moving');
this.entity.sprite.play('idle');
}
};
AnimationHandler.prototype.onKeyUp = function (event) {
// Check event.key to detect which key has been pressed
if (event.key === pc.KEY_UP) {
this.entity.sprite.stop('moving');
this.entity.sprite.play('idle');
}
};
AnimationHandler.prototype.onKeyUp = function (event) {
// Check event.key to detect which key has been pressed
if (event.key === pc.KEY_DOWN) {
this.entity.sprite.stop('moving');
this.entity.sprite.play('idle');
}
};
};
// swap method called for script hot-reloading
// inherit your script state here
// AnimationHandler.prototype.swap = function(old) { };
// to learn more about script anatomy, please read:
// http://developer.playcanvas.com/en/user-manual/scripting/
In the first section, I have code that detects when the sprite is moving and plays the moving sprite clip. I am trying to find a way (in the second half) to stop the moving animation and play the idle animation, but the moving clip just won’t stop.