How to set keyboard key press only once after pressing but not continuously

I am using below code to move the player up, but the problem is the button is pressed and held, the player keeps moving. How can I change this behavior so that no matter how long the button is pressed for the player, it only moves once?

if (cursor.up.isDown){
     player.body.velocity.y = -200;
     player.animations.stop('move');
}

      

+3


source to share


2 answers


Bool acting as a switch trigger should do the following job:

var flipFlop;

function update() {
    if (cursor.up.isDown){
        if (!flipFlop) {
            player.body.velocity.y = -200;
            player.animations.stop('move');
            flipFlop = true;
        }
    }

    if (cursor.up.isUp) {
        flipFlop = false;
    }
}

      



Note that the flipFlop variable is declared outside the update loop, otherwise it will be recreated every frame.

+4


source


Kamen Minkov's answer does work, but if your idea is to make a jump, the bool won't work, once you press the button, you can hit it with aghan and move on without even touching the ground.

But you can use this function to check if the body is touching down

function touchingDown(someone) {
var yAxis = p2.vec2.fromValues(0, 1);
var result = false;
for (var i = 0; i < game.physics.p2.world.narrowphase.contactEquations.length; i++) {
    var c = game.physics.p2.world.narrowphase.contactEquations[i];
    if (c.bodyA === someone.data || c.bodyB === someone.data)        {
        var d = p2.vec2.dot(c.normalA, yAxis); // Normal dot Y-axis
        if (c.bodyA === someone.data) d *= -1;
        if (d > 0.5) result = true;
    }
} return result;
}

      



and the call to send the body

if ( (cursor.up.isDown) && (touchingDown(player.body)) ){
        player.body.velocity.y = -200;
        player.animations.stop('move');
}

      

OBS: Function for P2 Physics, but for arcade, the body already has a field that says if it touches.

+1


source







All Articles