This repository has been archived by the owner on Oct 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrafty.js
13011 lines (11743 loc) · 426 KB
/
crafty.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
/**
* craftyjs 0.6.3
* http://craftyjs.com/
*
* Copyright 2014, Louis Stowasser
* Dual licensed under the MIT or GPL licenses.
*/
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var Crafty = require('./core.js'),
document = window.document,
HashMap = require('./HashMap.js');
// Crafty._rectPool
//
// This is a private object used internally by 2D methods
// Cascade and _attr need to keep track of an entity's old position,
// but we want to avoid creating temp objects every time an attribute is set.
// The solution is to have a pool of objects that can be reused.
//
// The current implementation makes a BIG ASSUMPTION: that if multiple rectangles are requested,
// the later one is recycled before any preceding ones. This matches how they are used in the code.
// Each rect is created by a triggered event, and will be recycled by the time the event is complete.
Crafty._rectPool = (function () {
var pool = [],
pointer = 0;
return {
get: function (x, y, w, h) {
if (pool.length <= pointer)
pool.push({});
var r = pool[pointer++];
r._x = x;
r._y = y;
r._w = w;
r._h = h;
return r;
},
copy: function (o) {
if (pool.length <= pointer)
pool.push({});
var r = pool[pointer++];
r._x = o._x;
r._y = o._y;
r._w = o._w;
r._h = o._h;
return r;
},
recycle: function (o) {
pointer--;
}
};
})();
/**@
* #Crafty.map
* @category 2D
* Functions related with querying entities.
* @see Crafty.HashMap
*/
Crafty.map = new HashMap();
var M = Math,
Mc = M.cos,
Ms = M.sin,
PI = M.PI,
DEG_TO_RAD = PI / 180;
Crafty.extend({
zeroFill: function (number, width) {
width -= number.toString().length;
if (width > 0)
return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
return number.toString();
}
});
/**@
* #2D
* @category 2D
* Component for any entity that has a position on the stage.
* @trigger Move - when the entity has moved - { _x:Number, _y:Number, _w:Number, _h:Number } - Old position
* @trigger Invalidate - when the entity needs to be redrawn
* @trigger Rotate - when the entity is rotated - { cos:Number, sin:Number, deg:Number, rad:Number, o: {x:Number, y:Number}}
*/
Crafty.c("2D", {
/**@
* #.x
* @comp 2D
* The `x` position on the stage. When modified, will automatically be redrawn.
* Is actually a getter/setter so when using this value for calculations and not modifying it,
* use the `._x` property.
* @see ._attr
*/
_x: 0,
/**@
* #.y
* @comp 2D
* The `y` position on the stage. When modified, will automatically be redrawn.
* Is actually a getter/setter so when using this value for calculations and not modifying it,
* use the `._y` property.
* @see ._attr
*/
_y: 0,
/**@
* #.w
* @comp 2D
* The width of the entity. When modified, will automatically be redrawn.
* Is actually a getter/setter so when using this value for calculations and not modifying it,
* use the `._w` property.
*
* Changing this value is not recommended as canvas has terrible resize quality and DOM will just clip the image.
* @see ._attr
*/
_w: 0,
/**@
* #.h
* @comp 2D
* The height of the entity. When modified, will automatically be redrawn.
* Is actually a getter/setter so when using this value for calculations and not modifying it,
* use the `._h` property.
*
* Changing this value is not recommended as canvas has terrible resize quality and DOM will just clip the image.
* @see ._attr
*/
_h: 0,
/**@
* #.z
* @comp 2D
* The `z` index on the stage. When modified, will automatically be redrawn.
* Is actually a getter/setter so when using this value for calculations and not modifying it,
* use the `._z` property.
*
* A higher `z` value will be closer to the front of the stage. A smaller `z` value will be closer to the back.
* A global Z index is produced based on its `z` value as well as the GID (which entity was created first).
* Therefore entities will naturally maintain order depending on when it was created if same z value.
*
* `z` is required to be an integer, e.g. `z=11.2` is not allowed.
* @see ._attr
*/
_z: 0,
/**@
* #.rotation
* @comp 2D
* The rotation state of the entity, in clockwise degrees.
* `this.rotation = 0` sets it to its original orientation; `this.rotation = 10`
* sets it to 10 degrees clockwise from its original orientation;
* `this.rotation = -10` sets it to 10 degrees counterclockwise from its
* original orientation, etc.
*
* When modified, will automatically be redrawn. Is actually a getter/setter
* so when using this value for calculations and not modifying it,
* use the `._rotation` property.
*
* `this.rotation = 0` does the same thing as `this.rotation = 360` or `720` or
* `-360` or `36000` etc. So you can keep increasing or decreasing the angle for continuous
* rotation. (Numerical errors do not occur until you get to millions of degrees.)
*
* The default is to rotate the entity around its (initial) top-left corner; use
* `.origin()` to change that.
*
* @see ._attr, .origin
*/
_rotation: 0,
/**@
* #.alpha
* @comp 2D
* Transparency of an entity. Must be a decimal value between 0.0 being fully transparent to 1.0 being fully opaque.
*/
_alpha: 1.0,
/**@
* #.visible
* @comp 2D
* If the entity is visible or not. Accepts a true or false value.
* Can be used for optimization by setting an entities visibility to false when not needed to be drawn.
*
* The entity will still exist and can be collided with but just won't be drawn.
* @see Crafty.DrawManager.draw, Crafty.DrawManager.drawAll
*/
_visible: true,
/**@
* #._globalZ
* @comp 2D
* When two entities overlap, the one with the larger `_globalZ` will be on top of the other.
* @see Crafty.DrawManager.draw, Crafty.DrawManager.drawAll
*/
_globalZ: null,
_origin: null,
_mbr: null,
_entry: null,
_children: null,
_parent: null,
_changed: false,
_define2DProperties: function () {
Object.defineProperty(this, 'x', {
set: function (v) {
this._attr('_x', v);
},
get: function () {
return this._x;
},
configurable: true,
enumerable: true
});
Object.defineProperty(this, '_x', {enumerable:false});
Object.defineProperty(this, 'y', {
set: function (v) {
this._attr('_y', v);
},
get: function () {
return this._y;
},
configurable: true,
enumerable: true
});
Object.defineProperty(this, '_y', {enumerable:false});
Object.defineProperty(this, 'w', {
set: function (v) {
this._attr('_w', v);
},
get: function () {
return this._w;
},
configurable: true,
enumerable: true
});
Object.defineProperty(this, '_w', {enumerable:false});
Object.defineProperty(this, 'h', {
set: function (v) {
this._attr('_h', v);
},
get: function () {
return this._h;
},
configurable: true,
enumerable: true
});
Object.defineProperty(this, '_h', {enumerable:false});
Object.defineProperty(this, 'z', {
set: function (v) {
this._attr('_z', v);
},
get: function () {
return this._z;
},
configurable: true,
enumerable: true
});
Object.defineProperty(this, '_z', {enumerable:false});
Object.defineProperty(this, 'rotation', {
set: function (v) {
this._attr('_rotation', v);
},
get: function () {
return this._rotation;
},
configurable: true,
enumerable: true
});
Object.defineProperty(this, '_rotation', {enumerable:false});
Object.defineProperty(this, 'alpha', {
set: function (v) {
this._attr('_alpha', v);
},
get: function () {
return this._alpha;
},
configurable: true,
enumerable: true
});
Object.defineProperty(this, '_alpha', {enumerable:false});
Object.defineProperty(this, 'visible', {
set: function (v) {
this._attr('_visible', v);
},
get: function () {
return this._visible;
},
configurable: true,
enumerable: true
});
Object.defineProperty(this, '_visible', {enumerable:false});
},
init: function () {
this._globalZ = this[0];
this._origin = {
x: 0,
y: 0
};
// offsets for the basic bounding box
this._bx1 = 0;
this._bx2 = 0;
this._by1 = 0;
this._by2 = 0;
this._children = [];
this._define2DProperties();
//insert self into the HashMap
this._entry = Crafty.map.insert(this);
//when object changes, update HashMap
this.bind("Move", function (e) {
// Choose the largest bounding region that exists
var area = this._cbr || this._mbr || this;
this._entry.update(area);
// Move children (if any) by the same amount
if (this._children.length > 0) {
this._cascade(e);
}
});
this.bind("Rotate", function (e) {
// Choose the largest bounding region that exists
var old = this._cbr || this._mbr || this;
this._entry.update(old);
// Rotate children (if any) by the same amount
if (this._children.length > 0) {
this._cascade(e);
}
});
//when object is removed, remove from HashMap and destroy attached children
this.bind("Remove", function () {
if (this._children) {
for (var i = 0; i < this._children.length; i++) {
// delete the child's _parent link, or else the child will splice itself out of
// this._children while destroying itself (which messes up this for-loop iteration).
delete this._children[i]._parent;
// Destroy child if possible (It's not always possible, e.g. the polygon attached
// by areaMap has no .destroy(), it will just get garbage-collected.)
if (this._children[i].destroy) {
this._children[i].destroy();
}
}
this._children = [];
}
if (this._parent) {
this._parent.detach(this);
}
Crafty.map.remove(this);
this.detach();
});
},
/**@
* #.offsetBoundary
* @comp 2D
* Extends the MBR of the entity by a specified amount.
*
* @trigger BoundaryOffset - when the MBR offset changes
* @sign public this .offsetBoundary(Number dx1, Number dy1, Number dx2, Number dy2)
* @param dx1 - Extends the MBR to the left by this amount
* @param dy1 - Extends the MBR upward by this amount
* @param dx2 - Extends the MBR to the right by this amount
* @param dy2 - Extends the MBR downward by this amount
*
* @sign public this .offsetBoundary(Number offset)
* @param offset - Extend the MBR in all directions by this amount
*
* You would most likely use this function to ensure that custom canvas rendering beyond the extent of the entity's normal bounds is not clipped.
*/
offsetBoundary: function(x1, y1, x2, y2){
if (arguments.length === 1)
y1 = x2 = y2 = x1;
this._bx1 = x1;
this._bx2 = x2;
this._by1 = y1;
this._by2 = y2;
this.trigger("BoundaryOffset");
this._calculateMBR();
return this;
},
/**
* Calculates the MBR when rotated some number of radians about an origin point o.
* Necessary on a rotation, or a resize
*/
_calculateMBR: function () {
var ox = this._origin.x + this._x,
oy = this._origin.y + this._y,
rad = -this._rotation * DEG_TO_RAD;
// axis-aligned (unrotated) coordinates, relative to the origin point
var dx1 = this._x - this._bx1 - ox,
dx2 = this._x + this._w + this._bx2 - ox,
dy1 = this._y - this._by1 - oy,
dy2 = this._y + this._h + this._by2 - oy;
var ct = Math.cos(rad),
st = Math.sin(rad);
// Special case 90 degree rotations to prevent rounding problems
ct = (ct < 1e-10 && ct > -1e-10) ? 0 : ct;
st = (st < 1e-10 && st > -1e-10) ? 0 : st;
// Calculate the new points relative to the origin, then find the new (absolute) bounding coordinates!
var x0 = dx1 * ct + dy1 * st,
y0 = - dx1 * st + dy1 * ct,
x1 = dx2 * ct + dy1 * st,
y1 = - dx2 * st + dy1 * ct,
x2 = dx2 * ct + dy2 * st,
y2 = - dx2 * st + dy2 * ct,
x3 = dx1 * ct + dy2 * st,
y3 = - dx1 * st + dy2 * ct,
minx = Math.floor(Math.min(x0, x1, x2, x3) + ox),
miny = Math.floor(Math.min(y0, y1, y2, y3) + oy),
maxx = Math.ceil(Math.max(x0, x1, x2, x3) + ox),
maxy = Math.ceil(Math.max(y0, y1, y2, y3) + oy);
if (!this._mbr) {
this._mbr = {
_x: minx,
_y: miny,
_w: maxx - minx,
_h: maxy - miny
};
} else {
this._mbr._x = minx;
this._mbr._y = miny;
this._mbr._w = maxx - minx;
this._mbr._h = maxy - miny;
}
// If a collision hitbox exists AND sits outside the entity, find a bounding box for both.
// `_cbr` contains information about a bounding circle of the hitbox.
// The bounds of `_cbr` will be the union of the `_mbr` and the bounding box of that circle.
// This will not be a minimal region, but since it's only used for the broad phase pass it's good enough.
//
// cbr is calculated by the `_checkBounds` method of the "Collision" component
if (this._cbr) {
var cbr = this._cbr;
var cx = cbr.cx, cy = cbr.cy, r = cbr.r;
var cx2 = ox + (cx + this._x - ox) * ct + (cy + this._y - oy) * st;
var cy2 = oy - (cx + this._x - ox) * st + (cy + this._y - oy) * ct;
cbr._x = Math.min(cx2 - r, minx);
cbr._y = Math.min(cy2 - r, miny);
cbr._w = Math.max(cx2 + r, maxx) - cbr._x;
cbr._h = Math.max(cy2 + r, maxy) - cbr._y;
}
},
/**
* Handle changes that need to happen on a rotation
*/
_rotate: function (v) {
var theta = -1 * (v % 360); //angle always between 0 and 359
var difference = this._rotation - v;
// skip if there's no rotation!
if (difference === 0)
return;
else
this._rotation = v;
//Calculate the new MBR
var rad = theta * DEG_TO_RAD,
o = {
x: this._origin.x + this._x,
y: this._origin.y + this._y
};
this._calculateMBR();
//trigger "Rotate" event
var drad = difference * DEG_TO_RAD,
ct = Math.cos(rad),
st = Math.sin(rad);
this.trigger("Rotate", {
cos: Math.cos(drad),
sin: Math.sin(drad),
deg: difference,
rad: drad,
o: o
});
},
/**@
* #.area
* @comp 2D
* @sign public Number .area(void)
* Calculates the area of the entity
*/
area: function () {
return this._w * this._h;
},
/**@
* #.intersect
* @comp 2D
* @sign public Boolean .intersect(Number x, Number y, Number w, Number h)
* @param x - X position of the rect
* @param y - Y position of the rect
* @param w - Width of the rect
* @param h - Height of the rect
* @sign public Boolean .intersect(Object rect)
* @param rect - An object that must have the `x, y, w, h` values as properties
* Determines if this entity intersects a rectangle. If the entity is rotated, its MBR is used for the test.
*/
intersect: function (x, y, w, h) {
var rect, mbr = this._mbr || this;
if (typeof x === "object") {
rect = x;
} else {
rect = {
x: x,
y: y,
w: w,
h: h
};
}
return mbr._x < rect.x + rect.w && mbr._x + mbr._w > rect.x &&
mbr._y < rect.y + rect.h && mbr._h + mbr._y > rect.y;
},
/**@
* #.within
* @comp 2D
* @sign public Boolean .within(Number x, Number y, Number w, Number h)
* @param x - X position of the rect
* @param y - Y position of the rect
* @param w - Width of the rect
* @param h - Height of the rect
* @sign public Boolean .within(Object rect)
* @param rect - An object that must have the `_x, _y, _w, _h` values as properties
* Determines if this current entity is within another rectangle.
*/
within: function (x, y, w, h) {
var rect, mbr = this._mbr || this;
if (typeof x === "object") {
rect = x;
} else {
rect = {
_x: x,
_y: y,
_w: w,
_h: h
};
}
return rect._x <= mbr._x && rect._x + rect._w >= mbr._x + mbr._w &&
rect._y <= mbr._y && rect._y + rect._h >= mbr._y + mbr._h;
},
/**@
* #.contains
* @comp 2D
* @sign public Boolean .contains(Number x, Number y, Number w, Number h)
* @param x - X position of the rect
* @param y - Y position of the rect
* @param w - Width of the rect
* @param h - Height of the rect
* @sign public Boolean .contains(Object rect)
* @param rect - An object that must have the `_x, _y, _w, _h` values as properties.
* Determines if the rectangle is within the current entity. If the entity is rotated, its MBR is used for the test.
*/
contains: function (x, y, w, h) {
var rect, mbr = this._mbr || this;
if (typeof x === "object") {
rect = x;
} else {
rect = {
_x: x,
_y: y,
_w: w,
_h: h
};
}
return rect._x >= mbr._x && rect._x + rect._w <= mbr._x + mbr._w &&
rect._y >= mbr._y && rect._y + rect._h <= mbr._y + mbr._h;
},
/**@
* #.pos
* @comp 2D
* @sign public Object .pos(void)
* Returns the x, y, w, h properties as a rect object
* (a rect object is just an object with the keys _x, _y, _w, _h).
*
* The keys have an underscore prefix. This is due to the x, y, w, h
* properties being merely setters and getters that wrap the properties with an underscore (_x, _y, _w, _h).
*/
pos: function () {
return {
_x: (this._x),
_y: (this._y),
_w: (this._w),
_h: (this._h)
};
},
/**@
* #.mbr
* @comp 2D
* @sign public Object .mbr()
* Returns the minimum bounding rectangle. If there is no rotation
* on the entity it will return the rect.
*/
mbr: function () {
if (!this._mbr) return this.pos();
return {
_x: (this._mbr._x),
_y: (this._mbr._y),
_w: (this._mbr._w),
_h: (this._mbr._h)
};
},
/**@
* #.isAt
* @comp 2D
* @sign public Boolean .isAt(Number x, Number y)
* @param x - X position of the point
* @param y - Y position of the point
* Determines whether a point is contained by the entity. Unlike other methods,
* an object can't be passed. The arguments require the x and y value.
*
* The given point is tested against the first of the following that exists: a mapArea associated with "Mouse", the hitarea associated with "Collision", or the object's MBR.
*/
isAt: function (x, y) {
if (this.mapArea) {
return this.mapArea.containsPoint(x, y);
} else if (this.map) {
return this.map.containsPoint(x, y);
}
var mbr = this._mbr || this;
return mbr._x <= x && mbr._x + mbr._w >= x &&
mbr._y <= y && mbr._y + mbr._h >= y;
},
/**@
* #.move
* @comp 2D
* @sign public this .move(String dir, Number by)
* @param dir - Direction to move (n,s,e,w,ne,nw,se,sw)
* @param by - Amount to move in the specified direction
* Quick method to move the entity in a direction (n, s, e, w, ne, nw, se, sw) by an amount of pixels.
*/
move: function (dir, by) {
if (dir.charAt(0) === 'n') this.y -= by;
if (dir.charAt(0) === 's') this.y += by;
if (dir === 'e' || dir.charAt(1) === 'e') this.x += by;
if (dir === 'w' || dir.charAt(1) === 'w') this.x -= by;
return this;
},
/**@
* #.shift
* @comp 2D
* @sign public this .shift(Number x, Number y, Number w, Number h)
* @param x - Amount to move X
* @param y - Amount to move Y
* @param w - Amount to widen
* @param h - Amount to increase height
* Shift or move the entity by an amount. Use negative values
* for an opposite direction.
*/
shift: function (x, y, w, h) {
if (x) this.x += x;
if (y) this.y += y;
if (w) this.w += w;
if (h) this.h += h;
return this;
},
/**@
* #._cascade
* @comp 2D
* @sign public void ._cascade(e)
* @param e - An object describing the motion
* Move or rotate the entity's children according to a certain motion.
* This method is part of a function bound to "Move": It is used
* internally for ensuring that when a parent moves, the child also
* moves in the same way.
*/
_cascade: function (e) {
if (!e) return; //no change in position
var i = 0,
children = this._children,
l = children.length,
obj;
//rotation
if (("cos" in e) || ("sin" in e)) {
for (; i < l; ++i) {
obj = children[i];
if ('rotate' in obj) obj.rotate(e);
}
} else {
//use current position
var dx = this._x - e._x,
dy = this._y - e._y,
dw = this._w - e._w,
dh = this._h - e._h;
for (; i < l; ++i) {
obj = children[i];
obj.shift(dx, dy, dw, dh);
}
}
},
/**@
* #.attach
* @comp 2D
* @sign public this .attach(Entity obj[, .., Entity objN])
* @param obj - Child entity(s) to attach
* Sets one or more entities to be children, with the current entity (`this`)
* as the parent. When the parent moves or rotates, its children move or
* rotate by the same amount. (But not vice-versa: If you move a child, it
* will not move the parent.) When the parent is destroyed, its children are
* destroyed.
*
* For any entity, `this._children` is the array of its children entity
* objects (if any), and `this._parent` is its parent entity object (if any).
*
* As many objects as wanted can be attached, and a hierarchy of objects is
* possible by attaching.
*/
attach: function () {
var i = 0,
arg = arguments,
l = arguments.length,
obj;
for (; i < l; ++i) {
obj = arg[i];
if (obj._parent) {
obj._parent.detach(obj);
}
obj._parent = this;
this._children.push(obj);
}
return this;
},
/**@
* #.detach
* @comp 2D
* @sign public this .detach([Entity obj])
* @param obj - The entity to detach. Left blank will remove all attached entities
* Stop an entity from following the current entity. Passing no arguments will stop
* every entity attached.
*/
detach: function (obj) {
var i;
//if nothing passed, remove all attached objects
if (!obj) {
for (i = 0; i < this._children.length; i++) {
this._children[i]._parent = null;
}
this._children = [];
return this;
}
//if obj passed, find the handler and unbind
for (i = 0; i < this._children.length; i++) {
if (this._children[i] == obj) {
this._children.splice(i, 1);
}
}
obj._parent = null;
return this;
},
/**@
* #.origin
* @comp 2D
* @sign public this .origin(Number x, Number y)
* @param x - Pixel value of origin offset on the X axis
* @param y - Pixel value of origin offset on the Y axis
* @sign public this .origin(String offset)
* @param offset - Combination of center, top, bottom, middle, left and right
* Set the origin point of an entity for it to rotate around.
*
* @example
* ~~~
* this.origin("top left")
* this.origin("center")
* this.origin("bottom right")
* this.origin("middle right")
* ~~~
*
* @see .rotation
*/
origin: function (x, y) {
//text based origin
if (typeof x === "string") {
if (x === "centre" || x === "center" || x.indexOf(' ') === -1) {
x = this._w / 2;
y = this._h / 2;
} else {
var cmd = x.split(' ');
if (cmd[0] === "top") y = 0;
else if (cmd[0] === "bottom") y = this._h;
else if (cmd[0] === "middle" || cmd[1] === "center" || cmd[1] === "centre") y = this._h / 2;
if (cmd[1] === "center" || cmd[1] === "centre" || cmd[1] === "middle") x = this._w / 2;
else if (cmd[1] === "left") x = 0;
else if (cmd[1] === "right") x = this._w;
}
}
this._origin.x = x;
this._origin.y = y;
return this;
},
/**@
* #.flip
* @comp 2D
* @trigger Invalidate - when the entity has flipped
* @sign public this .flip(String dir)
* @param dir - Flip direction
*
* Flip entity on passed direction
*
* @example
* ~~~
* this.flip("X")
* ~~~
*/
flip: function (dir) {
dir = dir || "X";
if (!this["_flip" + dir]) {
this["_flip" + dir] = true;
this.trigger("Invalidate");
}
return this;
},
/**@
* #.unflip
* @comp 2D
* @trigger Invalidate - when the entity has unflipped
* @sign public this .unflip(String dir)
* @param dir - Unflip direction
*
* Unflip entity on passed direction (if it's flipped)
*
* @example
* ~~~
* this.unflip("X")
* ~~~
*/
unflip: function (dir) {
dir = dir || "X";
if (this["_flip" + dir]) {
this["_flip" + dir] = false;
this.trigger("Invalidate");
}
return this;
},
/**
* Method for rotation rather than through a setter
*/
rotate: function (e) {
var x2, y2;
x2 = (this._x + this._origin.x - e.o.x) * e.cos + (this._y + this._origin.y - e.o.y) * e.sin + (e.o.x - this._origin.x);
y2 = (this._y + this._origin.y - e.o.y) * e.cos - (this._x + this._origin.x - e.o.x) * e.sin + (e.o.y - this._origin.y);
this._attr('_rotation', this._rotation - e.deg);
this._attr('_x', x2 );
this._attr('_y', y2 );
},
/**@
* #._attr
* @comp 2D
* Setter method for all 2D properties including
* x, y, w, h, alpha, rotation and visible.
*/
_attr: function (name, value) {
// Return if there is no change
if (this[name] === value) {
return;
}
//keep a reference of the old positions
var old = Crafty._rectPool.copy(this);
var mbr;
//if rotation, use the rotate method
if (name === '_rotation') {
this._rotate(value); // _rotate triggers "Rotate"
//set the global Z and trigger reorder just in case
} else if (name === '_z') {
this._globalZ = parseInt(value + Crafty.zeroFill(this[0], 5), 10); //magic number 10^5 is the max num of entities
this.trigger("reorder");
//if the rect bounds change, update the MBR and trigger move
} else if (name === '_x' || name === '_y') {
// mbr is the minimal bounding rectangle of the entity
mbr = this._mbr;
if (mbr) {
mbr[name] -= this[name] - value;
// cbr is a non-minmal bounding rectangle that contains both hitbox and mbr
// It will exist only when the collision hitbox sits outside the entity
if (this._cbr){
this._cbr[name] -= this[name] - value;
}
}
this[name] = value;
this.trigger("Move", old);
} else if (name === '_h' || name === '_w') {
mbr = this._mbr;
var oldValue = this[name];
this[name] = value;
if (mbr) {
this._calculateMBR();
}
if (name === '_w') {
this.trigger("Resize", {
axis: 'w',
amount: value - oldValue
});
} else if (name === '_h') {
this.trigger("Resize", {
axis: 'h',
amount: value - oldValue
});
}
this.trigger("Move", old);
}
//everything will assume the value
this[name] = value;
// flag for redraw
this.trigger("Invalidate");
Crafty._rectPool.recycle(old);
}
});
/**@
* #Gravity
* @category 2D
* @trigger Moved - When entity has moved on y-axis a Moved event is triggered with an object specifying the old position {x: old_x, y: old_y}
*
* Adds gravitational pull to the entity.
*/
Crafty.c("Gravity", {
_gravityConst: 0.2,
_gy: 0,
_falling: true,
_anti: null,
init: function () {
this.requires("2D");
},
/**@
* #.gravity
* @comp Gravity
* @sign public this .gravity([comp])
* @param comp - The name of a component that will stop this entity from falling
*
* Enable gravity for this entity no matter whether comp parameter is not specified,
* If comp parameter is specified all entities with that component will stop this entity from falling.
* For a player entity in a platform game this would be a component that is added to all entities
* that the player should be able to walk on.
*
* @example
* ~~~
* Crafty.e("2D, DOM, Color, Gravity")
* .color("red")
* .attr({ w: 100, h: 100 })