-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollidable.js
56 lines (48 loc) · 1.56 KB
/
collidable.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
window.collidable_objects = {};
export async function initCollidable(app) {
app.ticker.add((delta) => {
Collidable.checkCollisions();
});
}
export class Collidable {
constructor(sprite, me, enenemies) {
this.sprite = sprite;
this.enenemies = enenemies;
this.me = me;
if (!(this.me in collidable_objects)) {
collidable_objects[this.me] = new Set();
}
collidable_objects[this.me].add(this);
}
checkCollision() {
let list = new Set();
for (let key of this.enenemies) {
if (key in collidable_objects) {
list = list.union(collidable_objects[key]);
}
}
for (let obj of list) {
// Adjust bullet positions relative to the screen
let bound = this.sprite.getBounds();
let bound2 = obj.sprite.getBounds();
if (bound.x < bound2.x + bound2.width &&
bound.x + bound.width > bound2.x &&
bound.y < bound2.y + bound2.height &&
bound.y + bound.height > bound2.y) {
obj.onCollision(this);
this.onCollision(obj);
collidable_objects[this.me].delete(this);
}
}
}
onCollision(object) {
throw new Error("Method 'abstractMethod()' must be implemented.");
}
static checkCollisions() {
for (let key in collidable_objects) {
for (let obj of collidable_objects[key]) {
obj.checkCollision();
}
}
}
}