-
Notifications
You must be signed in to change notification settings - Fork 33
/
boxbox.js
1553 lines (1417 loc) · 52.3 KB
/
boxbox.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2012 Greg Smith <[email protected]>
Released under the MIT license:
https://github.com/incompl/boxbox/blob/master/LICENSE
Created at Bocoup http://bocoup.com
*/
/**
* @_page_title boxbox
* @_page_css updoc-custom.css
* @_page_description api documentation
* @_page_home_path .
* @_page_compact_index
*/
// Erik Moller's requestAnimationFrame shim
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelRequestAnimationFrame = window[vendors[x]+
'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}());
(function() {
var DEGREES_PER_RADIAN = 57.2957795; // 180 / pi
/**
* @description global boxbox object
*/
window.boxbox = {};
// Make sure Box2D exists
if (Box2D === undefined) {
console.error('boxbox needs Box2d to work');
return;
}
// Object creation inspired by Crockford
// http://javascript.crockford.com/prototypal.html
function create(o) {
function F() {}
F.prototype = o;
return new F();
}
// A minimal extend for simple objects inspired by jQuery
function extend(target, o) {
if (target === undefined) {
target = {};
}
if (o !== undefined) {
for (var key in o) {
if (o.hasOwnProperty(key) && target[key] === undefined) {
target[key] = o[key];
}
}
}
return target;
}
// these look like imports but there is no cost here
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Math = Box2D.Common.Math.b2Math;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2World = Box2D.Dynamics.b2World;
var shapes = Box2D.Collision.Shapes;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2AABB = Box2D.Collision.b2AABB;
/**
* @_module boxbox
* @_params canvas, [options]
* @canvas element to render on
* @options
* <ul>
* @gravity (default {x:0, y:10}) can be horizontal, negative, etc
* @allowSleep (default true) bodies may sleep when they come to
* rest. a sleeping body is no longer being simulated, which can
* improve performance.
* @scale (default 30) scale for rendering in pixels / meter
* @tickFrequency (default 50) onTick events happen every tickFrequency milliseconds
* @collisionOutlines (default false) render outlines over everything for debugging collisions
* </ul>
* @return a new <a href="#name-World">World</a>
* @description
without options
<code>var canvasElem = document.getElementById("myCanvas");
var world = boxbox.createWorld(canvasElem);</code>
with options
<code>var canvasElem = document.getElementById("myCanvas");
var world = boxbox.createWorld(canvasElem, {
gravity: {x: 0, y: 20},
scale: 60
});</code>
*/
window.boxbox.createWorld = function(canvas, options) {
var world = create(World);
world._init(canvas, options);
return world;
};
var WORLD_DEFAULT_OPTIONS = {
gravity: {x:0, y:10},
allowSleep: true,
scale: 30,
tickFrequency: 50,
collisionOutlines: false
};
var JOINT_DEFAULT_OPTIONS = {
type: "distance",
allowCollisions: false
};
/**
* @header
* @description contains a single self-contained physics simulation
*/
var World = {
_ops: null,
_world: null,
_canvas: null,
_keydownHandlers: {},
_keyupHandlers: {},
_startContactHandlers: {},
_finishContactHandlers: {},
_impactHandlers: {},
_destroyQueue: [],
_impulseQueue: [],
_constantVelocities: {},
_constantForces: {},
_entities: {},
_nextEntityId: 0,
_cameraX: 0,
_cameraY: 0,
_onRender: [],
_onTick: [],
_creationQueue: [],
_positionQueue: [],
_init: function(canvasElem, options) {
var self = this;
var key;
var i;
var world;
var listener;
this._ops = extend(options, WORLD_DEFAULT_OPTIONS);
this._world = new b2World(new b2Vec2(this._ops.gravity.x,
this._ops.gravity.y),
true);
world = this._world;
this._canvas = canvasElem;
this._ctx = this._canvas.getContext("2d");
this._scale = this._ops.scale;
// Set up rendering on the provided canvas
if (this._canvas !== undefined) {
// debug rendering
if (this._ops.debugDraw) {
var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(this._canvas.getContext("2d"));
debugDraw.SetDrawScale(this._scale); // TODO update this if changed?
debugDraw.SetFillAlpha(0.3);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
}
// game loop (onTick events)
window.setInterval(function() {
var i;
var ctx;
for (i = 0; i < self._onTick.length; i++) {
ctx = self._onTick[i].ctx;
if (!ctx._destroyed) {
self._onTick[i].fun.call(ctx);
}
}
}, this._ops.tickFrequency);
// animation loop
(function animationLoop(){
var key;
var entity;
var v;
var impulse;
var f;
var toDestroy;
var id;
var o;
// set velocities for this step
for (key in self._constantVelocities) {
v = self._constantVelocities[key];
v.body.SetLinearVelocity(new b2Vec2(v.x, v.y),
v.body.GetWorldCenter());
}
// apply impulses for this step
for (i = 0; i < self._impulseQueue.length; i++) {
impulse = self._impulseQueue.pop();
impulse.body.ApplyImpulse(new b2Vec2(impulse.x, impulse.y),
impulse.body.GetWorldCenter());
}
// set forces for this step
for (key in self._constantForces) {
f = self._constantForces[key];
f.body.ApplyForce(new b2Vec2(f.x, f.y),
f.body.GetWorldCenter());
}
for (key in self._entities) {
entity = self._entities[key];
v = entity._body.GetLinearVelocity();
if (v.x > entity._ops.maxVelocityX) {
v.x = entity._ops.maxVelocityX;
}
if (v.x < -entity._ops.maxVelocityX) {
v.x = -entity._ops.maxVelocityX;
}
if (v.y > entity._ops.maxVelocityY) {
v.y = entity._ops.maxVelocityY;
}
if (v.y < -entity._ops.maxVelocityY) {
v.y = -entity._ops.maxVelocityY;
}
}
// destroy
for (i = 0; i < self._destroyQueue.length; i++) {
toDestroy = self._destroyQueue.pop();
id = toDestroy._id;
world.DestroyBody(toDestroy._body);
toDestroy._destroyed = true;
delete self._keydownHandlers[id];
delete self._startContactHandlers[id];
delete self._finishContactHandlers[id];
delete self._impactHandlers[id];
self._destroyQueue.splice(id, 1);
self._impulseQueue.splice(id, 1);
delete self._constantVelocities[id];
delete self._constantForces[id];
delete self._entities[id];
}
// framerate, velocity iterations, position iterations
world.Step(1 / 60, 10, 10);
// create
for (i = 0; i < self._creationQueue.length; i++) {
self.createEntity(self._creationQueue.pop());
}
// position
for (i = 0; i < self._positionQueue.length; i++) {
o = self._positionQueue.pop();
o.o.position.call(o.o, o.val);
}
// render stuff
self._canvas.width = self._canvas.width;
for (key in self._entities) {
entity = self._entities[key];
entity._draw(self._ctx,
entity.canvasPosition().x,
entity.canvasPosition().y);
}
for (i = 0; i < self._onRender.length; i++) {
self._onRender[i].fun.call(self._onRender[i].ctx, self._ctx);
}
world.ClearForces();
world.DrawDebugData();
window.requestAnimationFrame(animationLoop);
}());
// keyboard events
window.addEventListener('keydown', function(e) {
for (var key in self._keydownHandlers) {
if (!self._entities[key]._destroyed) {
self._keydownHandlers[key].call(self._entities[key], e);
}
}
}, false);
window.addEventListener('keyup', function(e) {
for (var key in self._keyupHandlers) {
if (!self._entities[key]._destroyed) {
self._keyupHandlers[key].call(self._entities[key], e);
}
}
}, false);
// contact events
listener = new Box2D.Dynamics.b2ContactListener();
listener.BeginContact = function(contact) {
var a = self._entities[contact.GetFixtureA().GetBody()._bbid];
var b = self._entities[contact.GetFixtureB().GetBody()._bbid];
for (var key in self._startContactHandlers) {
if (a._id === Number(key) && !a._destroyed) {
self._startContactHandlers[key].call(self._entities[key], b);
}
if (b._id === Number(key) && !b._destroyed) {
self._startContactHandlers[key].call(self._entities[key], a);
}
}
};
listener.EndContact = function(contact) {
var a = self._entities[contact.GetFixtureA().GetBody()._bbid];
var b = self._entities[contact.GetFixtureB().GetBody()._bbid];
for (var key in self._finishContactHandlers) {
if (a._id === Number(key) && !a._destroyed) {
self._finishContactHandlers[key].call(self._entities[key], b);
}
if (b._id === Number(key) && !b._destroyed) {
self._finishContactHandlers[key].call(self._entities[key], a);
}
}
};
listener.PostSolve = function(contact, impulse) {
var a = self._entities[contact.GetFixtureA().GetBody()._bbid];
var b = self._entities[contact.GetFixtureB().GetBody()._bbid];
for (var key in self._impactHandlers) {
if (a._id === Number(key) && !a._destroyed) {
self._impactHandlers[key].call(self._entities[key],
b,
impulse.normalImpulses[0],
impulse.tangentImpulses[0]);
}
if (b._id === Number(key) && !b._destroyed) {
self._impactHandlers[key].call(self._entities[key],
a,
impulse.normalImpulses[0],
impulse.tangentImpulses[0]);
}
}
};
world.SetContactListener(listener);
}
},
_addKeydownHandler: function(id, f) {
this._keydownHandlers[id] = f;
},
_addKeyupHandler: function(id, f) {
this._keyupHandlers[id] = f;
},
_addStartContactHandler: function(id, f) {
this._startContactHandlers[id] = f;
},
_addFinishContactHandler: function(id, f) {
this._finishContactHandlers[id] = f;
},
_addImpactHandler: function(id, f) {
this._impactHandlers[id] = f;
},
_destroy: function(obj) {
this._destroyQueue.push(obj);
},
_applyImpulse: function(id, body, x, y) {
this._impulseQueue.push({
id:id,
body:body,
x:x,
y:y
});
},
_setConstantVelocity: function(name, id, body, x, y) {
this._constantVelocities[name + id] = {
id:id,
body:body,
x:x,
y:y
};
},
_clearConstantVelocity: function(name, id) {
delete this._constantVelocities[name + id];
},
_setConstantForce: function(name, id, body, x, y) {
this._constantForces[name + id] = {
id:id,
body:body,
x:x,
y:y
};
},
_clearConstantForce: function(name, id) {
delete this._constantForces[name + id];
},
/**
* @_module world
* @_params [value]
* @value: {x,y}
* @return: {x,y}
* @description get or set the world's gravity
*/
gravity: function(value) {
if (value !== undefined) {
this._world.SetGravity(new b2Vec2(0, value));
}
var v = this._world.GetGravity();
return {x: v.x, y: v.y};
},
/**
* @_module world
* @_params options
* @options
* <ul>
* @name of this entity
* @x starting x coordinate for the center of the new entity
* @y starting y coordinate for the center of the new entity
* @type 'dynamic' or 'static'. static objects can't move
* @shape 'square' or 'circle' or 'polygon'
* @height for box (default 1)
* @width for box (default 1)
* @radius for circle (default 1)
* @points for polygon [{x,y}, {x,y}, {x,y}] must go clockwise
* must be convex
* @density (default 2)
* @friction (default 1)
* @restitution or bounciness (default .2)
* @active (default true) participates in collisions and dynamics
* @rotation (default 0) initial rotation in degrees
* @fixedRotation (default false) prevent entity from rotating
* @bullet (default false) perform expensive continuous
* collision detection
* @maxVelocityX Prevent entity from moving too fast either left or right
* @maxVelocityY Prevent entity from moving too fast either up or down
* @image file for rendering
* @imageOffsetX (default 0) for image
* @imageOffsetY (default 0) for image
* @imageStretchToFit (default false) for image
* @spriteSheet Image is a sprite sheet (default false)
* @spriteWidth Used with spriteSheet (default 16)
* @spriteHeight Used with spriteSheet (default 16)
* @spriteX Used with spriteSheet (default 0)
* @spriteY Used with spriteSheet (default 0)
* @color CSS color for rendering if no image is given (default 'gray')
* @borderColor CSS color for rendering the shape's border (default 'black')
* @borderWidth Width of the border. The border does not impact physics. (default 1)
* @draw custom draw function, params are context, x, and y
* @init a function that is run when the entity is created
* @onKeyDown keydown event handler
* @onKeyUp keyup event handler
* @onStartContact start contact event handler
* @onFinishContact finish contact event handler
* @onImpact impact event handler
* @onRender event handler on render
* @onTick event handler on tick
* </ul>
* @return a new <a href="#name-Entity">Entity</a>
* @description
<h2>Example</h2>
<code>var player = world.createEntity({
name: "player",
shape: "circle",
radius: 2
});</code>
<h2>Templates</h2>
You can pass multiple options objects. This allows for "templates"
with reusable defaults:
<code>var redCircleTemplate = {color: "red", shape: "circle", radius: 3};
world.createEntity(redCircleTemplate, {x: 5, y: 5});
world.createEntity(redCircleTemplate, {x: 10, y: 5});</code>
The options objects on the right take precedence.
<h2>Dollar Properties</h2>
You can provide options that start with a $ like this:
<code>var ball = world.createEntity({color: "red", $customValue: 15});</code>
These are passed onto the resulting entity as they are:
<code>ball.$customValue === 15</code>
This allows you to provide your own custom methods and properties.
*/
createEntity: function() {
var o = {};
var args = Array.prototype.slice.call(arguments);
args.reverse();
for (var key in args) {
extend(o, args[key]);
}
if (this._world.IsLocked()) {
this._creationQueue.push(o);
return;
}
var entity = create(Entity);
var id = this._nextEntityId++;
entity._init(this, o, id);
this._entities[id] = entity;
return entity;
},
/**
* @_module world
* @_params entity1, entity2, [options]
* @entity1 Entity on one side of the joint
* @entity2 Entity on the other side of the joint
* @options
* <ul>
* @enableMotor (default false)
* @type one of
* <ul>
* @distance these entities will always remain the same distance apart
* @revolute
* @gear
* @friction
* @prismatic
* @weld
* @pulley
* @mouse
* @line
* </ul>
* </ul>
* @description Experimental joint support.
* See <a href="http://box2d.org/">box2d documentation</a> for more
* info.
*/
createJoint: function(entity1, entity2, options) {
options = options || {};
options = extend(options, JOINT_DEFAULT_OPTIONS);
var type = options.type;
var joint;
if (type === "distance") {
joint = new Box2D.Dynamics.Joints.b2DistanceJointDef();
}
else if (type === "revolute") {
joint = new Box2D.Dynamics.Joints.b2RevoluteJointDef();
}
else if (type === "gear") {
joint = new Box2D.Dynamics.Joints.b2GearJointDef();
}
else if (type === "friction") {
joint = new Box2D.Dynamics.Joints.b2FrictionJointDef();
}
else if (type === "prismatic") {
joint = new Box2D.Dynamics.Joints.b2PrismaticJointDef();
}
else if (type === "weld") {
joint = new Box2D.Dynamics.Joints.b2WeldJointDef();
}
else if (type === "pulley") {
joint = new Box2D.Dynamics.Joints.b2PulleyJointDef();
}
else if (type === "mouse") {
joint = new Box2D.Dynamics.Joints.b2MouseJointDef();
}
else if (type === "line") {
joint = new Box2D.Dynamics.Joints.b2LineJointDef();
}
if (options.enableMotor) {
joint.enableMotor = true;
}
var jointPositionOnEntity1 = entity1._body.GetWorldCenter();
if (options.jointPositionOnEntity1) {
jointPositionOnEntity1.x += options.jointPositionOnEntity1.x;
jointPositionOnEntity1.y += options.jointPositionOnEntity1.y;
}
var jointPositionOnEntity2 = entity2._body.GetWorldCenter();
if (options.jointPositionOnEntity2) {
jointPositionOnEntity2.x += options.jointPositionOnEntity2.x;
jointPositionOnEntity2.y += options.jointPositionOnEntity2.y;
}
if (type === "mouse") {
joint.bodyA = entity1._body;
joint.bodyB = entity2._body;
}
else if (joint.Initialize) {
joint.Initialize(entity1._body,
entity2._body,
jointPositionOnEntity1,
jointPositionOnEntity2);
}
if (options.allowCollisions) {
joint.collideConnected = true;
}
this._world.CreateJoint(joint);
},
/**
* @_module world
* @x1 upper left of query box
* @y1 upper left of query box
* @x2 lower right of query box
* @y2 lower right of query box
* @return array of Entities. may be empty
* @description find Entities in a given query box
*/
find: function(x1, y1, x2, y2) {
if (x2 === undefined) {
x2 = x1;
}
if (y2 === undefined) {
y2 = y1;
}
var self = this;
var result = [];
var aabb = new b2AABB();
aabb.lowerBound.Set(x1, y1);
aabb.upperBound.Set(x2, y2);
this._world.QueryAABB(function(fixt) {
result.push(self._entities[fixt.GetBody()._bbid]);
return true;
}, aabb);
return result;
},
/**
* @_module world
* @_params [value]
* @value {x,y}
* @return {x,y}
* @description get or set position of camera
*/
camera: function(v) {
v = v || {};
if (v.x === undefined && v.y === undefined) {
return {x:this._cameraX, y: this._cameraY};
}
if (v.x !== undefined) {
this._cameraX = v.x;
}
if (v.y !== undefined) {
this._cameraY = v.y;
}
},
/**
* @_module world
* @callback function( context )
* <ul>
* @context canvas context for rendering
* @this World
* </ul>
* @description Add an onRender callback to the World
* This is useful for custom rendering. For example, to draw text
* on every frame:
* <code>world.onRender(function(ctx) {
* ctx.fillText("Score: " + score, 10, 10);
* });</code>
* This callback occurs after all entities have been rendered on the
* frame.
* <br>
* Multiple onRender callbacks can be added, and they can be removed
* with unbindOnRender.
*/
onRender: function(callback) {
this._onRender.push({
fun: callback,
ctx: this
});
},
/**
* @_module world
* @callback callback
* @description
* If the provided function is currently an onRender callback for this
* World, it is removed.
*/
unbindOnRender: function(callback) {
var newArray = [];
var i;
for (i = 0; i < this._onRender.length; i++) {
if (this._onRender[i].fun !== callback) {
newArray.push(this._onRender[i]);
}
}
this._onRender = newArray;
},
/**
* @_module world
* @callback function()
* <ul>
* @this World
* </ul>
* @description Add an onTick callback to the World
* <br>
* Ticks are periodic events that happen independant of rendering.
* You can use ticks as your "game loop". The default tick frequency
* is 50 milliseconds, and it can be set as an option when creating
* the world.
* <br>
* Multiple onTick callbacks can be added, and they can be removed
* with unbindOnTick.
*/
onTick: function(callback) {
this._onTick.push({
fun: callback,
ctx: this
});
},
/**
* @_module world
* @callback callback
* @description
* If the provided function is currently an onTick callback for this
* World, it is removed.
*/
unbindOnTick: function(callback) {
var newArray = [];
var i;
for (i = 0; i < this._onTick.length; i++) {
if (this._onTick[i].fun !== callback) {
newArray.push(this._onTick[i]);
}
}
this._onTick = newArray;
},
/**
* @_module world
* @_params [value]
* @value number
* @return number
* @description get or set the scale for rendering in pixels / meter
*/
scale: function(s) {
if (s !== undefined) {
this._scale = s;
// TODO update debug draw?
}
return this._scale;
},
/**
* @_module world
* @return {x,y}
* @description Get a canvas position for a corresponding world position. Useful
* for custom rendering in onRender. Respects world scale and camera position.
*/
canvasPositionAt: function(x, y) {
var c = this.camera();
var s = this.scale();
return {
x: Math.round((x + -c.x) * s),
y: Math.round((y + -c.y) * s)
};
}
};
var ENTITY_DEFAULT_OPTIONS = {
name: 'unnamed object',
x: 10,
y: 5,
type: 'dynamic', // or static
shape: 'square', // or circle or polygon
height: 1, // for box
width: 1, // for box
radius: 1, // for circle
points: [{x:0, y:0}, // for polygon
{x:2, y:0},
{x:0, y:2}],
density: 2,
friction: 1,
restitution: 0.2, // bounciness
active: true, // participates in collision and dynamics
rotation: null,
fixedRotation: false,
bullet: false, // perform expensive continuous collision detection
maxVelocityX: 1000,
maxVelocityY: 1000,
image: null,
imageOffsetX: 0,
imageOffsetY: 0,
imageStretchToFit: null,
color: 'gray',
borderColor: 'black',
borderWidth: 1,
spriteSheet: false,
spriteWidth: 16,
spriteHeight: 16,
spriteX: 0,
spriteY: 0,
init: null,
draw: function(ctx, x, y) {
var cameraOffsetX = -this._world._cameraX;
var cameraOffsetY = -this._world._cameraY;
ctx.fillStyle = this._ops.color;
ctx.strokeStyle = this._ops.borderColor;
ctx.lineWidth = this._ops.borderWidth;
var i;
var scale = this._world._scale;
var collisionOutlines = this._world._ops.collisionOutlines;
var ox = this._ops.imageOffsetX || 0;
var oy = this._ops.imageOffsetY || 0;
ox *= scale;
oy *= scale;
if (this._sprite !== undefined) {
var width;
var height;
if (this._ops.shape === "circle" && this._ops.imageStretchToFit) {
width = height = this._ops.radius * 2;
x -= this._ops.radius / 2 * scale;
y -= this._ops.radius / 2 * scale;
}
else if (this._ops.imageStretchToFit) {
width = this._ops.width;
height = this._ops.height;
}
else if (this._ops.spriteSheet) {
width = this._ops.spriteWidth / 30;
height = this._ops.spriteHeight / 30;
}
else {
width = this._sprite.width / 30;
height = this._sprite.height / 30;
}
var tx = ox + (x + width / 4 * scale);
var ty = oy + (y + height / 4 * scale);
ctx.translate(tx, ty);
ctx.rotate(this._body.GetAngle());
if (this._ops.spriteSheet) {
ctx.drawImage(this._sprite,
this._ops.spriteX * this._ops.spriteWidth,
this._ops.spriteY * this._ops.spriteHeight,
this._ops.spriteWidth,
this._ops.spriteHeight,
-(width / 2 * scale),
-(height / 2 * scale),
width * scale,
height * scale);
}
else {
ctx.drawImage(this._sprite,
-(width / 2 * scale),
-(height / 2 * scale),
width * scale,
height * scale);
}
ctx.rotate(0 - this._body.GetAngle());
ctx.translate(-tx, -ty);
}
if (this._sprite && !collisionOutlines) {
return;
}
if (collisionOutlines) {
if (this._sprite !== undefined) {
ctx.fillStyle = "transparent";
}
ctx.strokeStyle = "rgb(255, 0, 255)";
ctx.lineWidth = 2;
}
if (this._ops.shape === 'polygon' || this._ops.shape === 'square') {
var poly = this._body.GetFixtureList().GetShape();
var vertexCount = parseInt(poly.GetVertexCount(), 10);
var localVertices = poly.GetVertices();
var vertices = new Vector(vertexCount);
var xf = this._body.m_xf;
for (i = 0; i < vertexCount; ++i) {
vertices[i] = b2Math.MulX(xf, localVertices[i]);
}
ctx.beginPath();
ctx.moveTo((cameraOffsetX + vertices[0].x) * scale, (cameraOffsetY + vertices[0].y) * scale);
for (i = 1; i < vertices.length; i++) {
ctx.lineTo((cameraOffsetX + vertices[i].x) * scale, (cameraOffsetY + vertices[i].y) * scale);
}
ctx.closePath();
if (this._ops.borderWidth !== 0 || collisionOutlines) {
ctx.stroke();
}
ctx.fill();
}
else if (this._ops.shape === 'circle') {
var p = this.position();
ctx.beginPath();
ctx.arc((cameraOffsetX + p.x) * scale,
(cameraOffsetY + p.y) * scale,
this._ops.radius * scale,
0,
Math.PI * 2, true);
ctx.closePath();
if (this._ops.borderWidth !== 0 || collisionOutlines) {
ctx.stroke();
}
ctx.fill();
}
}
};
/**
* @header
* @description a single physical object in the physics simulation
*/
var Entity = {
_id: null,
_ops: null,
_body: null,
_world: null,
_init: function(world, options, id) {
var ops;
var op;
if (options && options.components !== undefined) {
options.components.reverse();
options.components.forEach(function(component) {
extend(options, component);
});
}
this._ops = extend(options, ENTITY_DEFAULT_OPTIONS);
ops = this._ops;
this._body = new b2BodyDef();
var body = this._body;
this._world = world;
this._id = id;
// $ props
for (op in this._ops) {
if (op.match(/^\$/)) {
this[op] = this._ops[op];
}
}
var fixture = new b2FixtureDef();
fixture.density = ops.density;
fixture.friction = ops.friction;
fixture.restitution = ops.restitution;
body.position.x = ops.x;
body.position.y = ops.y;
this._name = ops.name;
// type
if (ops.type === 'static') {
body.type = b2Body.b2_staticBody;
}
else if (ops.type === 'dynamic') {
body.type = b2Body.b2_dynamicBody;
}
// shape
if (ops.shape === 'square') {
fixture.shape = new shapes.b2PolygonShape();