Javascript KeyCodes在socket.io中不起作用

时间:2017-06-26 03:07:23

标签: javascript node.js socket.io

我有这个游戏项目,允许用户使用箭头键或WASD四处移动。我有这个代码来实现这个

在HTML文件中:

document.onkeydown = function(event){
    if(event.keycode === 87 || event.keycode === 38){
        socket.emit("keyPress",{input: "up", state: true});
    } else if(event.keyCode === 83 || event.keycode === 40){
        socket.emit("keyPress",{input: "down", state: true});
    } else if(event.keyCode === 65 || event.keycode === 37){
        socket.emit("keyPress",{input: "left", state: true});
    } else if(event.keyCode === 68 || event.keycode === 39){
        socket.emit("keyPress",{input: "right", state: true});
    }
};
document.onkeyup = function(event){
    if(event.keyCode == 87 || event.keycode === 38){
        socket.emit("keyPress",{input: "up", state: false});
    } else if(event.keyCode == 83 || event.keycode === 40){
        socket.emit("keyPress",{input: "down", state: false});
    } else if(event.keyCode == 65 || event.keycode === 37){
        socket.emit("keyPress",{input: "left", state: false});
    } else if(event.keyCode == 68 || event.keycode === 39){
        socket.emit("keyPress",{input: "right", state: false});
    }
};

现在在JavaScript文件中:

socket.on("keyPress",function(data){
    if(data.input == "up"){
        player.up = data.state;
    } else if(data.input == "down"){
        player.down = data.state;
    } else if(data.input == "left"){
        player.left = data.state;
    } else if(data.input == "right"){
        player.right = data.state;
    }
});
var Player = function(id){
    var self = {
        x: 250,
        y:250,
        id: id,
        up: false,
        down: false,
        left: false,
        right: false,
        speed: 5
    };
    self.updatePosition = function(){
        if(self.up){
            self.y -= self.speed;
        } else if(self.down){
            self.y += self.speed;
        } else if(self.left){
            self.x -= self.speed;
        } else if(self.right){
            self.x += self.speed;
        }
        if(self.x < 0){
            self.x = 0;
        } else if(self.x > 500){
            self.x = 500;
        } else if(self.y < 0){
        self.y = 0;
        } else if(self.y > 500){
            self.y = 500;
        }
    }
    return self;
}

但是,箭头键和W键都不起作用。 ASD键工作得很好。

为什么箭头键和W键不起作用?在代码中,KeyCodes是正确的,以及位置更新。我应该如何使它发挥作用?

0 个答案:

没有答案