如何在Node.js中发送真实数据?

时间:2019-04-01 07:52:14

标签: javascript node.js socket.io multiplayer

我在游戏服务器端,以60 FPS更新逻辑并以10 FPS发送数据

var PLAYER_LIST = {};

class Player {
    constructor(socket) {
        this.id = Math.random() * 9999;
        this.pressKeyAttack = 0;
        this.socket = socket;
        PLAYER_LIST[this.id] = this;
    }
    setupSocket() {
        this.socket.on("keypress", (data) => {
            if (data.key == 1) this.pressKeyAttack = data.value;
        });
    }
    send() {
        //Simple data
        //Send to this player all data from PLAYER_LIST
        var data = {};
        for (var id in PLAYER_LIST) {
            data[id] = PLAYER_LIST[id].pressKeyAttack;
        }
        this.socket.emit("data", data);
    }
    update() {
        if (this.pressKeyAttack == 1) {
            //do something
        }
    }
}

io.sockets.on("connection", (socket) => {
    new Player(socket);
});

setInterval(() => {
    //Logic update
    for (var id in PLAYER_LIST) {
        PLAYER_LIST[id].update();
    }
}, 1000 / 60);

setInterval(() => {
    //Send data
    for (var id in PLAYER_LIST) {
        PLAYER_LIST[id].send();
    }
}, 1000 / 10);

示例客户端,当任何玩家按[Space]时,所有其他玩家都将看到该玩家的动画。

var PLAYER_LIST = {}; //all player

for (var id in PLAYER_LIST) {
    if (PLAYER_LIST[id].pressKeyAttack == 1) {
        //run animation
    }
}

socket.on("data", (data) => {
    for (var id in data) {
        PLAYER_LIST[id].pressKeyAttack = data[id];
    }
})

document.onkeydown = function(e) {
    // Player.pressKeyAttack = 1
    if (e.keyCode == 32) socket.emit("keypress", { key: 1, value: 1 });
}

document.onkeyup = function(e) {
    // Player.pressKeyAttack = 0
    if (e.keyCode == 32) socket.emit("keypress", { key: 1, value: 0 });
}

我的问题:

例如:我是一名游戏玩家(称为Player_A),还有一些其他玩家。当Player_A如此快地上下按[Space]时,其他播放器无法从Player_A接收数据(pressKeyAttack = 1),因为循环发送数据运行10 FPS(每100ms发送一次),Player_A.pressKeyAttack等于1并返回0 50毫秒。

看起来像:

at 0ms: Player_A.pressKeyAttack = 0;

at 20ms: Player_A.pressKeyAttack = 1; //Player press down

at 50ms: Player_A.pressKeyAttack = 0; //Player press up

at 100ms: Loop Data Run - Player_A.pressKeyAttack = 0.

实际上它曾经是1。如何解决此问题?

0 个答案:

没有答案