-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (83 loc) · 2.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var io = require('socket.io-client');
var fit = require('canvas-fit');
var loop = require('raf-loop');
var socket = io();
var xtend = require('xtend');
var keyDown = require('key-pressed');
const {ACTIONS, EVENTS, KEY_BINDINGS} = require('./lib/constants');
var Minimap = require('./lib/minimap');
var Renderer = require('./lib/renderer');
var Statusbar = require('./lib/statusbar');
var lerpObject = require('./lib/lerp-object');
var renderer = new Renderer();
var minimap = new Minimap();
var statusbar = new Statusbar(socket);
var frames = [];
var delay = 40;
var avgPing = 0;
var pingArr = [];
var maxPingArrSize = 100;
var avgGameStep = 0;
var gameStepArr = [];
var maxGameStepArr = [];
socket.on('step', function(worldState) {
frames.push(worldState);
if (frames.length > 10) {
frames.shift();
}
pingArr.push(Date.now() - worldState.timestamp);
avgPing = pingArr.reduce((a, b) => a + b) / pingArr.length;
if (pingArr.length > maxPingArrSize) {
pingArr.shift();
}
gameStepArr.push(worldState.delta);
avgGameStep = gameStepArr.reduce((a, b) => a + b) / gameStepArr.length;
if (gameStepArr.length > maxGameStepArr) {
gameStepArr.shift();
}
delay = avgPing + (avgGameStep * 1.5)
});
window.addEventListener('keydown', emitActions);
window.addEventListener('keyup', emitActions);
var engine = loop(step).start();
function step(dt) {
statusbar.setLatestRenderStep(dt);
statusbar.setTargetDelay(delay);
var targetTime = Date.now() - delay;
var foo = findFramesBetweenTime(targetTime);
var frameA = xtend(foo[0]);
var frameB = xtend(foo[1]);
if (!frameA || !frameB) {
console.warn('skipping frame');
return;
}
var lerpScale = Math.abs((1/frameB.delta) * (frameA.timestamp - targetTime));
var worldState = lerpObject(frameA, frameB, lerpScale);
minimap.render(worldState);
renderer.render(worldState);
}
function findFramesBetweenTime(time) {
for(var i = 0; i < frames.length; i++) {
var frame = frames[i];
if (frame.timestamp >= time && (frame.timestamp - frame.delta) <= time) {
return [frames[i - 1], frames[i]];
}
}
return [];
}
function emitActions () { var actions = {};
Object.keys(KEY_BINDINGS)
.filter(function(action) {
return KEY_BINDINGS[action].some(pressed);
})
.forEach(function(action) {
actions[action] = true;
});
socket.emit('action', actions);
}
function pressed(vkey) {
return vkey.split('+')
.every(function(key) {
return key[0] === '!' ? !keyDown(key.slice(1)) : keyDown(key);
});
}