我使用的多人游戏似乎在玩家移动io.emit的同时传输玩家屏幕位置数据,我认为这必须是服务器的压力,我怎样才能调整这个代码每250个执行不超过一次MS?
// Only emit if the player is moving
if (this.speed != 0) {
this.emitPlayerData()
}
},
emitPlayerData () {
// Emit the 'move-player' event, updating the player's data on the server
socket.emit('move-player', {
x: this.sprite.body.x,
y: this.sprite.body.y,
angle: this.sprite.body.rotation,
答案 0 :(得分:3)
您可以使用debounce
功能。
if (this.speed != 0) {
this.emitPlayerData()
}
将是
if (this.speed != 0) {
debounce(this.emitPlayerData, 250, true)
}
请注意debounce API,即debounce(expensiveFunction, ms, immediate)
去抖功能示例
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
有关更多信息和示例:
如果你在内部使用lodash,那就去吧! https://www.npmjs.com/package/lodash.debounce
答案 1 :(得分:1)
您可以创建临时时间戳来检查上次发送数据的时间,并且只有在超过250毫秒之前才会发出。例如:
var lastUpdated = Date.now(); //get current timestamp
if (this.speed != 0 && lastUpdated + 250 <= Date.now()) { // if last updated timestamp + 250ms is smaller than current timestamp
lastUpdated = Date.now(); //update the lastUpdated timestamp
this.emitPlayerData();
}
答案 2 :(得分:1)
理论上,您可以使用
之类的内容忽略特定事件的发生// Only emit if the player is moving
if (this.speed != 0)
{
this.emitPlayerData()
}
var blockEmit = false;
emitPlayerData ()
{
if (!blockEmit)
{
// Emit the 'move-player' event, updating the player's data on the server
socket.emit('move-player', {
x: this.sprite.body.x,
y: this.sprite.body.y,
angle: this.sprite.body.rotation,
}
blockEmit = true;
setTimeout(function () {
blockEmit = false;
}, 250)
}
}
这取决于你是如何做到这一点以及你想如何实现它,但这是主要的想法