As visible from the picture, I am struggling to force the gameobject’s body to stay in position, specially when performing the animation from stab, significantly wider than the default (bottom-left corner) after having flipped left. This is a case of the body shifting left, as the animation stays in place and it does not overflow to the right as it could be misunderstood from the picture.
A possible workaround I imagine is to set the body offset an amount of pixels to the right during that particular animation, however I feel reluctant to do this as it seems ‘hacky’.
As I’m new to the framework this is the bare bones code to make the man move and stab so far.
let stabOnCooldown = false;
let onStab = false;
function create ()
{
player= this.physics.add.sprite(500, 500, 'animation-default').setScale(2).setSize(37, 64, false);
//animations, keys
}
function moveRight() {
player.setFlip(false, false);
player.setVelocityX(speed);
player.anims.play('walk', true);
}
function moveLeft() {
player.setFlip(true, false);
player.setVelocityX(-speed);
player.anims.play('walk', true);
}
function stop() {
player.setVelocityX(0)
player.anims.play('still',true);
}
function update ()
{
//Perform a stab if 'x' is pressed
if (attackKey.X.isDown && !stabOnCooldown) {
onStab = true;
stabOnCooldown = true;
player.setVelocityX(0);
player.anims.play('stab', true);
//stab cooldown logic: perform stab 1/4 of a second and disable it for half a second afterwards
setTimeout(function() {
onStab = false;
setTimeout(function() {
stabOnCooldown = false;
}, 500);
}, 250);
}
else if (horizontalMoveKeys.RIGHT.isDown && !onStab) {moveRight();}
else if (horizontalMoveKeys.LEFT.isDown && !onStab) {moveLeft();}
else if (!onStab) {stop();}
}