forked from Jezzamonn/fourier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conductor.js
79 lines (63 loc) · 2.35 KB
/
conductor.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
export default class Conductor {
constructor(controllers) {
this.lastTime = Date.now();
this.mousePosition = null;
this.controllers = controllers.slice();
this.updatingControllers = [];
// We can handle these all the same really.
document.addEventListener('mousemove', (evt) => this.updateMousePosition(evt));
document.addEventListener('mousedown', (evt) => this.updateMousePosition(evt));
document.addEventListener('mouseup', (evt) => this.updateMousePosition(evt));
document.addEventListener('touchmove', (evt) => this.updateTouchPosition(evt));
document.addEventListener('touchstart', (evt) => this.updateTouchPosition(evt));
document.addEventListener('touchend', (evt) => this.updateTouchPosition(evt));
window.addEventListener('resize', (evt) => this.onResize(evt));
}
start() {
// Kick off the update loop
window.requestAnimationFrame(() => this.everyFrame());
}
onResize(evt) {
this.controllers.forEach(controller => {
if (typeof controller.onResize === 'function') {
controller.onResize();
}
})
}
everyFrame() {
this.update();
this.render();
requestAnimationFrame(() => this.everyFrame());
}
update() {
let curTime = Date.now();
let dt = (curTime - this.lastTime) / 1000;
this.updatingControllers = [];
this.controllers.forEach(controller => {
if (controller.isOnScreen()) {
controller.update(dt, this.mousePosition);
this.updatingControllers.push(controller);
}
});
this.lastTime = curTime;
const debug = document.getElementById('debug-content');
if (debug) {
debug.innerHTML = this.updatingControllers.map(c => c.id).join('<br>') + '<br>';
}
}
render() {
this.controllers.forEach(controller => {
if (controller.isOnScreen()) {
controller.render();
}
});
}
updateMousePosition(evt) {
this.mousePosition = { x: evt.clientX, y: evt.clientY };
}
updateTouchPosition(evt) {
if (evt.touches.length > 0) {
this.mousePosition = { x: evt.touches[0].clientX, y: evt.touches[0].clientY };
}
}
}