-
Notifications
You must be signed in to change notification settings - Fork 0
/
PhysicsSystem.js
302 lines (254 loc) · 8.34 KB
/
PhysicsSystem.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//--------------------
/**
* PhysicsSystem
**/
(function() {
// Box2d vars
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2World = Box2D.Dynamics.b2World;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2Listener = Box2D.Dynamics.b2ContactListener;
var SCALE = 16;
var TIMESTEP = 1 / 30;
var PhysicsSystem = function() {
this.world = null;
this.b2world = null;
this.bodies = null;
this.staticBodies = null;
this.bodiesByEntity = null;
this.contacts = [];
this.fixedTimestepAccumulator = 0;
};
PhysicsSystem.prototype.addToWorld = function(world) {
// world of entities
this.world = world;
// box2d world
this.b2world = new b2World(new b2Vec2(0, 0), false);
this.bodies = [];
this.staticBodies = [];
this.bodiesByEntity = {};
//contact listener
var system = this;
var listener = new b2Listener();
listener.BeginContact = function(contact) {
var entA = contact.GetFixtureA().GetBody().GetUserData();
var entB = contact.GetFixtureB().GetBody().GetUserData();
system.contacts.push({a: entA, b: entB});
//console.log('BeginContact');
};
listener.PostSolve = function(contact, impulse) {
//console.log('PostSolve');
};
this.b2world.SetContactListener(listener);
/* debugDraw
var debugDraw = new b2DebugDraw();
var debugCanvas = document.getElementById('debugCanvas');
var debugContext = debugCanvas.getContext('2d');
debugDraw.SetSprite(debugContext);
debugDraw.SetDrawScale(SCALE);
debugDraw.SetFillAlpha(0.7);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
this.b2world.SetDebugDraw(debugDraw);
//*/
};
PhysicsSystem.prototype.removeFromWorld = function() {
this.world = null;
this.b2world = null;
this.bodies = null;
this.staticBodies = null;
};
PhysicsSystem.prototype.step = function(delta) {
var bodies = this.bodies;
var world = this.world;
var bodiesByEntity = this.bodiesByEntity;
// delete removed bodies
for (var eid in bodiesByEntity) {
var ent = world.getEntityById(eid);
if (!ent || !ent.has('rigidBody')) {
var body = bodiesByEntity[eid];
this.b2world.DestroyBody(body);
delete bodiesByEntity[eid];
}
}
// fix bodies without position
var entsWithBody = this.world.getEntities('rigidBody');
for (var i = 0, ent; !!(ent = entsWithBody[i]); i++) {
// bodies must have position
var position = ent.get('position');
if (!position) {
position = {x: 0, y: 0};
ent.add('position', position);
}
}
// create added bodies
for (var i = 0, ent; !!(ent = entsWithBody[i]); i++) {
// if ent does not have a body, create it
var body = bodiesByEntity[ent.id];
if (!body) {
body = this._createBody(ent);
}
}
this.clearCollisions();
this.handleMoveTo();
//* == position ==
for (var i = 0, l = bodies.length; i < l; i++) {
var body = bodies[i];
var entity = body.GetUserData();
var position = entity.get('position');
position.x = body.GetWorldCenter().x * SCALE;
position.y = body.GetWorldCenter().y * SCALE;
}
// == position == */
// ==velocity==
var velEnts = this.world.getEntities('velocity');
for (var i = 0, ent; !!(ent = velEnts[i]); i++) {
var velocity = ent.get('velocity');
var dBody = this.bodiesByEntity[ent.id];
var v = dBody.GetLinearVelocity();
v.x = velocity.x;
v.y = velocity.y;
dBody.SetLinearVelocity(v);
//ent.del('velocity');
}
// ==velocity==
this.stepBox2DWorld(delta);
this.updateBodiesPosition();
// ==velocity==
var velEnts = this.world.getEntities('velocity');
for (var i = 0, ent; !!(ent = velEnts[i]); i++) {
var velocity = ent.get('velocity');
var dBody = this.bodiesByEntity[ent.id];
var v = dBody.GetLinearVelocity();
if (v.x || v.y) {
velocity.x = v.x;
velocity.y = v.y;
} else {
ent.del('velocity');
}
}
// ==velocity==
this.setCollisions();
};
PhysicsSystem.prototype.clearCollisions = function() {
var collidedEnts = this.world.getEntities('collision');
for (var i = 0, ent; !!(ent = collidedEnts[i]); i++) {
ent.del('collision');
}
};
PhysicsSystem.prototype.stepBox2DWorld = function(delta) {
this.fixedTimestepAccumulator += delta / 1000.0;
while (this.fixedTimestepAccumulator >= TIMESTEP) {
this.b2world.Step(TIMESTEP, 8, 3);
this.fixedTimestepAccumulator -= TIMESTEP;
}
//this.b2world.DrawDebugData();
};
PhysicsSystem.prototype.updateBodiesPosition = function() {
var bodies = this.bodies;
for (var i = 0, l = bodies.length; i < l; i++) {
var body = bodies[i];
var entity = body.GetUserData();
var position = entity.get('position');
position.x = body.GetWorldCenter().x * SCALE;
position.y = body.GetWorldCenter().y * SCALE;
}
};
PhysicsSystem.prototype.setCollisions = function() {
for (var i = 0, len = this.contacts.length; i < len; i++) {
var contact = this.contacts[i];
contact.a.add('collision', {other: contact.b});
contact.b.add('collision', {other: contact.a});
}
this.contacts.length = 0;
};
PhysicsSystem.prototype.handleMoveTo = function() {
var ent = this.world.getEntities('moveTo')[0];
if (ent) {
var posX = ent.get('moveTo').x;
ent.del('moveTo');
var bodyToMove = null;
var bodies = this.bodies;
for (var i = 0, l = bodies.length; i < l; i++) {
var body = bodies[i];
if (body.GetUserData().id === ent.id)
{
bodyToMove = body;
break;
}
}
if (bodyToMove) {
var p = bodyToMove.GetPosition();
p.x = posX / SCALE;
bodyToMove.SetPosition(p);
}
}
};
PhysicsSystem.prototype._createBody = function(entity) {
var rigidBody = entity.get('rigidBody'),
position = entity.get('position');
if (rigidBody.bodyType !== 'static') {
var bodyTypeMap = {
'kinematic': b2Body.b2_kinematicBody,
'dynamic': b2Body.b2_dynamicBody
};
// ent.add('rigidBody', {bodyType : 'dynamic', w: 2 * BLOCK, h: 1 * BLOCK});
var fixture = new b2FixtureDef;
fixture.density = 1;
fixture.restitution = 1;
fixture.friction = 0;
if (rigidBody.isSensor) {
fixture.isSensor = true;
}
if (rigidBody.type === 'ball' && false) {
var rad = 0.5 * rigidBody.w;
fixture.shape = new b2CircleShape(rad / SCALE);
} else {
fixture.shape = new b2PolygonShape;
fixture.shape.SetAsBox(0.5 * rigidBody.w / SCALE, 0.5 * rigidBody.h / SCALE);
}
var bodyDef = new b2BodyDef;
// get body def by colision type
bodyDef.type = bodyTypeMap[rigidBody.bodyType];
bodyDef.position.x = position.x / SCALE;
bodyDef.position.y = position.y / SCALE;
bodyDef.fixedRotation = true;
var body = this.b2world.CreateBody(bodyDef);
body.CreateFixture(fixture);
body.SetUserData(entity);
this.bodies.push(body);
this.bodiesByEntity[entity.id] = body;
return body;
} else {
// == body ==
var bodyDef = new b2BodyDef;
bodyDef.type = b2Body.b2_staticBody;
bodyDef.position.x = position.x / SCALE;
bodyDef.position.y = position.y / SCALE;
// == body ==
var body = this.b2world.CreateBody(bodyDef);
// == body ==
// == fixture ==
var fixtureDef = new b2FixtureDef;
fixtureDef.density = 1;
fixtureDef.restitution = 1;
fixtureDef.friction = 0;
fixtureDef.shape = new b2PolygonShape;
fixtureDef.shape.SetAsBox(0.5 * rigidBody.w / SCALE, 0.5 * rigidBody.h / SCALE);
// == fixture ==
body.CreateFixture(fixtureDef);
// == fixture ==
// ==
body.SetUserData(entity);
this.bodies.push(body);
this.bodiesByEntity[entity.id] = body;
return body;
}
};
window.PhysicsSystem = PhysicsSystem;
})();