Javascript keyevents for a game

74 views Asked by At

I am making a game where on clicking the spacebar the player moves from left to right. and again on clicking the spacebar the player will move from right to left. I have done the coding using keyevents but its not working.

game.prototype.start_handling = function()
{
var that = this;

$(document).on('keydown.game' , function(e)
{
    that.key_down(e);
    return false;
});

$(document).on('keyup.game' ,function(e)
{
    that.key_up(e);
    return false;
});
}
game.prototype.key_down = function(e)
{
var code = e.keyCode;
var f1 = true;
var f2 = false;
if(code == 32 && f1 == true)
{
    this.player.jump();
    this.player.do_move_right = true;
    f1 = false;
    f2 = true;
}
if(code == 32 && f2 == true)
 {
    this.player.jump();
    this.player.do_move_left = true;
    this.player.do_move_right = true;
    f1 = true;
    f2 = false;
 } 
}
game.prototype.key_up = function(e)
{
var code = e.keyCode;
var f1 = true;
var f2 = false;
if(code == 32 && f1 == true)
{
    this.player.jump();
    this.player.do_move_right = true;
    f1 = false;
    f2 = true;
}
if(code == 32 && f2 == true)
 {
    this.player.jump();
    this.player.do_move_left = true;
    this.player.do_move_right = true;
    f1 = true;
    f2 = false;
 } 
}

I have change it and applied... but still its not working. I want the player to move from left to right on clicking space and then stop and then again on clicking space the player will move back from right to left.

2

There are 2 answers

1
Pasang Sherpa On

You are checking for same condition twice ..

var code = e.keyCode;
if (code == 32) {
    if(!this.player.do_move_right) {
        this.player.jump();
        this.player.do_move_right = true;
    } else {
        this.player.jump();
        this.player.do_move_right = false;
    }
}
1
Eduard Maralyan On

Are you add a listener like this < body onkeyup = "myfunction()">

function myfunction(){
    var code = window.event.keyCode;
   // your code
}