使用socket.io输入键盘

时间:2017-04-27 17:46:59

标签: socket.io sprite

目前我已经能够使用鼠标移动精灵,但我仍然坚持让它使用键盘移动

缩短客户端代码:

var Client = {};
Client.socket = io.connect();

Client.sendClick = function(x,y){
    Client.socket.emit('click',{x:x,y:y});
};

Client.socket.on('move',function(data){
    Game.movePlayer(data.id,data.x,data.y);
});

缩短服务器代码:

socket.on('click',function(data){
        console.log('click to '+data.x+', '+data.y);
        socket.player.x = data.x;
        socket.player.y = data.y;
        io.emit('move',socket.player);
    });

我在这些方面尝试了一些东西

Client.sendKey = function(data){
switch(data.keyCode)
{
    case 40:    
     Client.socket.emit('movement', data.y - 10);
     break;
  case 38: 
     Client.socket.emit('movement', data.y + 10);
     break;
  case 37:    
     Client.socket.emit('movement', data.x - 10);
     break;
  case 39:     
     Client.socket.emit('movement', data.x + 10);
     break;
}
});

1 个答案:

答案 0 :(得分:0)

这将是如何在游戏循环场景中处理键码的示例,如果您不将其用作游戏的一部分,也可以是可塑的。我也假设你使用JavaScript,但如果我错了,我会删除这个答案。

//keys array
var keys = [];

//Bind document event listeners
document.addEventListener('keyup', keyUp);
document.addEventListener('keydown', keyDown);


function moveClient(KeyCodeArr) {

    //if a key code is true then it means the key has been pressed.

    if (KeyCodeArr[40]) {
        Client.socket.emit('movement', data.y - 10);
    }

    if (KeyCodeArr[38]) {
        Client.socket.emit('movement', data.y + 10);
    }

    if (KeyCodeArr[37]) {
        Client.socket.emit('movement', data.x - 10);
    }

    if (KeyCodeArr[39]) {
        Client.socket.emit('movement', data.x + 10);
    }

}

/**
 * These two events handle
 */

//key down event for use with listener
function keyDown(event) {
    keys[event.keyCode] = true;

}

//key up event for use with event listener
function keyUp(event) {
    keys[event.keyCode] = false;
}

//main in this example would be a game loop.
function main() {
    moveClient();
}