-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathentity.js
74 lines (59 loc) · 1.72 KB
/
entity.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
import _ from 'lodash';
export default class Entity {
constructor() {
// Each entity had a unique ID.
this.uid = _.uniqueId();
// Each entity has a number of components.
this.c = {};
Object.seal(this.c);
// World this entity has been added to.
this.world = null;
}
// Attach a component to the entity.
attach(component) {
// Check component's dependencies are met.
_.each(component.$deps, dependencyID => {
if (!this.has(dependencyID)) {
console.error(`${dependencyID} component missing.`);
throw new Error('ComponentDependencyMissing');
}
});
// Check component is not already attached.
if (this.has(component.$id)) {
throw new Error('ComponentAlreadyAttached');
}
// Attach component.
const newC = {...this.c};
newC[component.$id] = component;
Object.seal(newC);
this.c = newC;
// If the entity has already been added to a world, rebuild it.
if (this.world) {
this.world.rebuild(this, component.$id);
}
return this;
}
// Remove a component from the entity.
detach(componentId) {
// Check that the component was not a dependency.
_.each(this.c, component => {
const dependencyExists = _.some(component.$deps, dep => dep === componentId);
if (dependencyExists) {
console.error(`${component.$id} depends on ${componentId}`);
throw new Error('ComponentDependencyMissing');
}
});
// Detach the component.
const newC = {...this.c};
delete newC[componentId];
Object.seal(newC);
this.c = newC;
if (this.world) {
this.world.rebuild(this);
}
return this;
}
has(componentId) {
return _.has(this.c, componentId);
}
}