-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathworld.js
59 lines (54 loc) · 1.42 KB
/
world.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
"use strict";
var util = require('util');
var events = require('events');
var Vector = require('./vector');
function World(width, height) {
events.EventEmitter.call(this);
this.entities = [];
this.width = width || 0;
this.height = height || 0;
}
util.inherits(World, events.EventEmitter);
World.prototype.update = function(dt) {
this.entities.forEveryPair(function(e1, e2) {
e1.interactWith(e2)
});
this.entities.forEach(function(e) {
e.update(dt);
e.bounceOffWalls(this.width, this.height);
}, this);
this.emit('update');
return this;
};
World.prototype.clear = function(e) {
this.entities = [];
};
World.prototype.addEntity = function(e) {
var i = 0;
while(this.entities[i] !== undefined)
i++;
e._id = i;
this.entities[i] = e;
this.emit('entity.add', e);
return this;
};
World.prototype.removeEntity = function(e) {
if(e && e._id in this.entities) {
this.emit('entity.remove', e);
delete this.entities[e._id];
}
return this;
};
World.prototype.randomPosition = function() {
return new Vector(Math.random()*this.width, Math.random()*this.height);
},
World.prototype.entityById = function(id) {
for(i in this.entities) {
var e = this.entities[i]
if(e._id == id) return e;
}
};
Object.defineProperty(World.prototype, 'totalMass', {get: function() {
return this.entities.reduce(function(sum, e) { return e.mass + sum; }, 0);
}});
module.exports = World;