【发布时间】:2022-11-06 15:59:36
【问题描述】:
所以我正在尝试使用 JavaScript 和 WebSockets 编写一个简单的在线多人游戏。 我目前正在努力解决滞后问题: 为此,我测量了包含玩家更新位置的消息从玩家的计算机到服务器,然后到所有其他玩家的计算机所花费的时间,然后我根据该位置向该位置施加物理力数量。 我使用播放器类上的方法应用了物理,如下所示:
// dt is deltaTime
update(dt) {
const groundLevel = 350;
this.yVal += this.weight * dt;
this.y += this.yVal * dt;
if (this.y > groundLevel) {
while (this.y > groundLevel) {
this.y -= this.yVal / Math.abs(this.yVal);
}
this.yVal = 0;
}
this.xVal /= this.friction * dt;
this.x += this.xVal * dt;
}
然后我在获取更新位置时重复调用该函数,如下所示:
// p is the player
// data is the object sent by the server containing the required data, and data.data is the player's transform data.
p.setData(data.data);
// 16.4 is about 1/60 seconds - simulating the average fps of 60
// data.time is the time when the message was sent.
let timeTook = new Date().getTime() - data.time;
for (let i = 0; i < timeTook ; i += 16.4) {
p.update(16.4);
}
这适用于 y 位置: 正如您在this clip 中看到的那样 - 我模拟了 1 秒的延迟 - 在 1 秒延迟之后,对象跳到它应该出现的确切位置。
然而,当我尝试向左或向右移动玩家时,位置变得很偏离! 正如您在this clip 中看到的那样 - 具有相同的滞后 - 对象在一个窗口中的移动比在另一个窗口中移动得更远。
我不知道为什么会发生这种情况,或者为什么它只发生在 x 位置,我希望能得到任何帮助。
【问题讨论】:
标签: javascript websocket game-development multiplayer