-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameengine.js
81 lines (66 loc) · 2.07 KB
/
gameengine.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
// This game shell was happily modified from Googler Seth Ladd's "Bad Aliens" game and his Google IO talk in 2011
class GameEngine {
constructor() {
this.entities = [];
this.ctx = null;
this.surfaceWidth = null;
this.surfaceHeight = null;
};
init(ctx) { // called after page has loaded
this.ctx = ctx;
this.surfaceWidth = this.ctx.canvas.width;
this.surfaceHeight = this.ctx.canvas.height;
this.startInput();
this.timer = new Timer();
};
start() {
var that = this;
(function gameLoop() {
that.loop();
requestAnimFrame(gameLoop, that.ctx.canvas);
})();
};
startInput() {
var getXandY = function (e) {
var x = e.clientX - that.ctx.canvas.getBoundingClientRect().left;
var y = e.clientY - that.ctx.canvas.getBoundingClientRect().top;
return { x: x, y: y };
}
var that = this;
this.ctx.canvas.addEventListener("click", function (e) {
that.click = getXandY(e);
}, false);
this.ctx.canvas.addEventListener("mousemove", function (e) {
that.mouse = getXandY(e);
}, false);
};
addEntity(entity) {
this.entities.push(entity);
};
draw() {
this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
for (var i = 0; i < this.entities.length; i++) {
this.entities[i].draw(this.ctx);
}
};
update() {
var entitiesCount = this.entities.length;
for (var i = 0; i < entitiesCount; i++) {
var entity = this.entities[i];
if (!entity.removeFromWorld) {
entity.update();
}
}
for (var i = this.entities.length - 1; i >= 0; --i) {
if (this.entities[i].removeFromWorld) {
this.entities.splice(i, 1);
}
}
};
loop() {
this.clockTick = this.timer.tick();
this.update();
this.draw();
this.click = null;
};
};