游戏的Javascript键事件

问题描述 投票:-3回答:2

我正在制作一个游戏,在单击空格键时,玩家从左到右移动。然后再次单击空格键,播放器将从右移到左。我已经使用keyevents完成了编码,但无法正常工作。

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;
 } 
}

我已经对其进行了更改并应用了...但是仍然无法正常工作。我希望播放器在单击空间时从左移至右,然后停下来,然后再次单击空间,播放器将从右移至左。

javascript dom-events keyboard-events event-listener keystroke
2个回答
0
投票

您正在两次检查相同的状况..

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
投票

您是否添加了这样的侦听器

function myfunction(){
    var code = window.event.keyCode;
   // your code
} 
© www.soinside.com 2019 - 2024. All rights reserved.