-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathentity.js
65 lines (54 loc) · 1.79 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
const createTransform = require('./transform')
const assert = require('assert')
let entityId = 0
function Entity(components, tags, renderer) {
assert(!tags || Array.isArray(tags), 'Entity tags must be an array or null')
this.id = entityId++
this.tags = tags || []
this.renderer = renderer
this.components = components ? components.slice(0) : []
this.componentsMap = new Map()
this.components.forEach((component) => {
this.componentsMap.set(component.type, component)
})
this.transform = this.getComponent('Transform')
if (!this.transform) {
this.transform = createTransform({
parent: null
})
this.addComponent(this.transform)
}
this.components.forEach((component) => component.init(this))
}
Entity.prototype.dispose = function() {
this.components.forEach((component) => {
if (component.dispose) {
component.dispose()
}
})
// detach from the hierarchy
this.transform.set({ parent: null })
}
Entity.prototype.addComponent = function(component) {
this.components.push(component)
this.componentsMap.set(component.type, component)
component.init(this)
}
Entity.prototype.removeComponent = function(component) {
var idx = this.components.indexOf(component)
assert(idx !== -1, `Removing component that doesn't belong to this entity`)
this.components.splice(idx, 1)
this.componentsMap.delete(component.type)
this.components.forEach((otherComponent) => {
if (otherComponent.type === component.type) {
this.componentsMap.set(otherComponent.type, otherComponent)
}
})
}
// Only the last added component of that type will be returned
Entity.prototype.getComponent = function(type) {
return this.componentsMap.get(type)
}
module.exports = function createEntity(components, parent, tags) {
return new Entity(components, parent, tags)
}