-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgameengine.js
More file actions
104 lines (85 loc) · 2.88 KB
/
gameengine.js
File metadata and controls
104 lines (85 loc) · 2.88 KB
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
101
102
103
104
// gameengine.js
// This game shell was happily modified from Googler Seth Ladd's "Bad Aliens" game and his Google IO talk in 2011
class GameEngine {
constructor(options) {
// What you will use to draw
// Documentation: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
this.ctx = null;
// Everything that will be updated and drawn each frame
this.entities = [];
// ECS Systems
this.systems = [];
// Information on the input
this.click = null;
this.mouse = null;
this.wheel = null;
this.keys = {};
// Options and the Details
this.options = options || {
debugging: false,
};
};
init(ctx) {
this.ctx = ctx;
this.startInput();
this.timer = new Timer();
};
start() {
this.running = true;
const gameLoop = () => {
this.loop();
requestAnimFrame(gameLoop, this.ctx.canvas);
};
gameLoop();
};
startInput() {
const getXandY = e => ({
x: e.clientX - this.ctx.canvas.getBoundingClientRect().left,
y: e.clientY - this.ctx.canvas.getBoundingClientRect().top
});
this.ctx.canvas.addEventListener("mousemove", e => {
if (this.options.debugging) {
console.log("MOUSE_MOVE", getXandY(e));
}
this.mouse = getXandY(e);
});
this.ctx.canvas.addEventListener("click", e => {
if (this.options.debugging) {
console.log("CLICK", getXandY(e));
}
this.click = getXandY(e);
});
this.ctx.canvas.addEventListener("wheel", e => {
if (this.options.debugging) {
console.log("WHEEL", getXandY(e), e.wheelDelta);
}
e.preventDefault(); // Prevent Scrolling
this.wheel = e;
});
this.ctx.canvas.addEventListener("contextmenu", e => {
if (this.options.debugging) {
console.log("RIGHT_CLICK", getXandY(e));
}
e.preventDefault(); // Prevent Context Menu
this.rightclick = getXandY(e);
});
this.ctx.canvas.addEventListener("keydown", event => this.keys[event.key] = true);
this.ctx.canvas.addEventListener("keyup", event => this.keys[event.key] = false);
};
addEntity(entity) {
this.entities.push(entity);
};
addSystem(system) {
this.systems.push(system);
};
loop() {
this.clockTick = this.timer.tick();
// Run all systems
for (let system of this.systems) {
system.update(this.clockTick, this);
}
// Remove entities marked for removal
this.entities = this.entities.filter(e => !e.removeFromWorld);
};
};
// KV Le was here :)