-
Notifications
You must be signed in to change notification settings - Fork 0
/
crafty-dirty.js
10642 lines (9621 loc) · 306 KB
/
crafty-dirty.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
/*!
* Crafty v0.5.3
* http://craftyjs.com
*
* Copyright 2010, Louis Stowasser
* Dual licensed under the MIT or GPL licenses.
*/
(function (window, initComponents, undefined) {
/**@
* #Crafty
* @category Core
* Select a set of or single entities by components or an entity's ID.
*
* Crafty uses syntax similar to jQuery by having a selector engine to select entities by their components.
*
* @example
* ~~~
* Crafty("MyComponent")
* Crafty("Hello 2D Component")
* Crafty("Hello, 2D, Component")
* ~~~
*
* The first selector will return all entities that have the component `MyComponent`. The second will return all entities that have `Hello` and `2D` and `Component` whereas the last will return all entities that have at least one of those components (or).
*
* ~~~
* Crafty("*")
* ~~~
* Passing `*` will select all entities.
*
* ~~~
* Crafty(1)
* ~~~
* Passing an integer will select the entity with that `ID`.
*
* Finding out the `ID` of an entity can be done by returning the property `0`.
* ~~~
* var ent = Crafty.e("2D");
* ent[0]; //ID
* ~~~
*/
var Crafty = function (selector) {
return new Crafty.fn.init(selector);
},
GUID, FPS, frame, components, entities, handlers, onloads, tick, requestID,
noSetter, loops, milliSecPerFrame, nextGameTick, slice, rlist, rspace,
initState = function () {
GUID = 1; //GUID for entity IDs
FPS = 50;
frame = 1;
components = {}; //map of components and their functions
entities = {}; //map of entities and their data
entityFactories = {}; //templates of entities
handlers = {}; //global event handlers
onloads = []; //temporary storage of onload handlers
tick;
/*
* `window.requestAnimationFrame` or its variants is called for animation.
* `.requestID` keeps a record of the return value previous `window.requestAnimationFrame` call.
* This is an internal variable. Used to stop frame.
*/
requestID;
noSetter;
loops = 0;
milliSecPerFrame = 1000 / FPS;
nextGameTick = (new Date).getTime();
slice = Array.prototype.slice;
rlist = /\s*,\s*/;
rspace = /\s+/;
};
initState();
/**@
* #Crafty Core
* @category Core
* @trigger NewEntityName - After setting new name for entity - String - entity name
* @trigger NewComponent - when a new component is added to the entity - String - Component
* @trigger RemoveComponent - when a component is removed from the entity - String - Component
* @trigger Remove - when the entity is removed by calling .destroy()
*
* Set of methods added to every single entity.
*/
Crafty.fn = Crafty.prototype = {
init: function (selector) {
//select entities by component
if (typeof selector === "string") {
var elem = 0, //index elements
e, //entity forEach
current,
and = false, //flags for multiple
or = false,
del,
comps,
score,
i, l;
if (selector === '*') {
for (e in entities) {
this[+e] = entities[e];
elem++;
}
this.length = elem;
return this;
}
//multiple components OR
if (selector.indexOf(',') !== -1) {
or = true;
del = rlist;
//deal with multiple components AND
} else if (selector.indexOf(' ') !== -1) {
and = true;
del = rspace;
}
//loop over entities
for (e in entities) {
if (!entities.hasOwnProperty(e)) continue; //skip
current = entities[e];
if (and || or) { //multiple components
comps = selector.split(del);
i = 0;
l = comps.length;
score = 0;
for (; i < l; i++) //loop over components
if (current.__c[comps[i]]) score++; //if component exists add to score
//if anded comps and has all OR ored comps and at least 1
if (and && score === l || or && score > 0) this[elem++] = +e;
} else if (current.__c[selector]) this[elem++] = +e; //convert to int
}
//extend all common components
if (elem > 0 && !and && !or) this.extend(components[selector]);
if (comps && and) for (i = 0; i < l; i++) this.extend(components[comps[i]]);
this.length = elem; //length is the last index (already incremented)
// if there's only one entity, return the actual entity
if (elem === 1) {
return entities[this[elem-1]];
}
} else { //Select a specific entity
if (!selector) { //nothin passed creates God entity
selector = 0;
if (!(selector in entities)) entities[selector] = this;
}
//if not exists, return undefined
if (!(selector in entities)) {
this.length = 0;
return this;
}
this[0] = selector;
this.length = 1;
//update from the cache
if (!this.__c) this.__c = {};
//update to the cache if NULL
if (!entities[selector]) entities[selector] = this;
return entities[selector]; //return the cached selector
}
return this;
},
/**@
* #.setName
* @comp Crafty Core
* @sign public this .setName(String name)
* @param name - A human readable name for debugging purposes.
*
* @example
* ~~~
* this.setName("Player");
* ~~~
*/
setName: function (name) {
var entityName = String(name);
this._entityName = entityName;
this.trigger("NewEntityName", entityName);
return this;
},
/**@
* #.addComponent
* @comp Crafty Core
* @sign public this .addComponent(String componentList)
* @param componentList - A string of components to add separated by a comma `,`
* @sign public this .addComponent(String Component1[, .., String ComponentN])
* @param Component# - Component ID to add.
* Adds a component to the selected entities or entity.
*
* Components are used to extend the functionality of entities.
* This means it will copy properties and assign methods to
* augment the functionality of the entity.
*
* There are multiple methods of adding components. Passing a
* string with a list of component names or passing multiple
* arguments with the component names.
*
* If the component has a function named `init` it will be called.
*
* @example
* ~~~
* this.addComponent("2D, Canvas");
* this.addComponent("2D", "Canvas");
* ~~~
*/
addComponent: function (id) {
var uninit = [], c = 0, ul, //array of components to init
i = 0, l, comps, comp;
//add multiple arguments
if (arguments.length > 1) {
l = arguments.length;
for (; i < l; i++) {
this.__c[arguments[i]] = true;
uninit.push(arguments[i]);
}
//split components if contains comma
} else if (id.indexOf(',') !== -1) {
comps = id.split(rlist);
l = comps.length;
for (; i < l; i++) {
this.__c[comps[i]] = true;
uninit.push(comps[i]);
}
//single component passed
} else {
this.__c[id] = true;
uninit.push(id);
}
//extend the components
ul = uninit.length;
for (; c < ul; c++) {
comp = components[uninit[c]];
this.extend(comp);
//if constructor, call it
if (comp && "init" in comp) {
comp.init.call(this);
}
}
this.trigger("NewComponent", uninit);
return this;
},
/**@
* #.toggleComponent
* @comp Crafty Core
* @sign public this .toggleComponent(String ComponentList)
* @param ComponentList - A string of components to add or remove separated by a comma `,`
* @sign public this .toggleComponent(String Component1[, .., String componentN])
* @param Component# - Component ID to add or remove.
* Add or Remove Components from an entity.
*
* @example
* ~~~
* var e = Crafty.e("2D,DOM,Test");
* e.toggleComponent("Test,Test2"); //Remove Test, add Test2
* e.toggleComponent("Test,Test2"); //Add Test, remove Test2
* ~~~
*
* ~~~
* var e = Crafty.e("2D,DOM,Test");
* e.toggleComponent("Test","Test2"); //Remove Test, add Test2
* e.toggleComponent("Test","Test2"); //Add Test, remove Test2
* e.toggleComponent("Test"); //Remove Test
* ~~~
*/
toggleComponent:function(toggle){
var i = 0, l, comps;
if (arguments.length > 1) {
l = arguments.length;
for (; i < l; i++) {
if(this.has(arguments[i])){
this.removeComponent(arguments[i]);
}else{
this.addComponent(arguments[i]);
}
}
//split components if contains comma
} else if (toggle.indexOf(',') !== -1) {
comps = toggle.split(rlist);
l = comps.length;
for (; i < l; i++) {
if(this.has(comps[i])){
this.removeComponent(comps[i]);
}else{
this.addComponent(comps[i]);
}
}
//single component passed
} else {
if(this.has(toggle)){
this.removeComponent(toggle);
}else{
this.addComponent(toggle);
}
}
return this;
},
/**@
* #.requires
* @comp Crafty Core
* @sign public this .requires(String componentList)
* @param componentList - List of components that must be added
*
* Makes sure the entity has the components listed. If the entity does not
* have the component, it will add it.
*
* @see .addComponent
*/
requires: function (list) {
var comps = list.split(rlist),
i = 0, l = comps.length,
comp;
//loop over the list of components and add if needed
for (; i < l; ++i) {
comp = comps[i];
if (!this.has(comp)) this.addComponent(comp);
}
return this;
},
/**@
* #.removeComponent
* @comp Crafty Core
* @sign public this .removeComponent(String Component[, soft])
* @param component - Component to remove
* @param soft - Whether to soft remove it (defaults to `true`)
*
* Removes a component from an entity. A soft remove (the default) will only
* refrain `.has()` from returning true. Hard will remove all
* associated properties and methods.
*
* @example
* ~~~
* var e = Crafty.e("2D,DOM,Test");
* e.removeComponent("Test"); //Soft remove Test component
* e.removeComponent("Test", false); //Hard remove Test component
* ~~~
*/
removeComponent: function (id, soft) {
if (soft === false) {
var props = components[id], prop;
for (prop in props) {
delete this[prop];
}
}
delete this.__c[id];
this.trigger("RemoveComponent", id);
return this;
},
/**@
* #.has
* @comp Crafty Core
* @sign public Boolean .has(String component)
* Returns `true` or `false` depending on if the
* entity has the given component.
*
* For better performance, simply use the `.__c` object
* which will be `true` if the entity has the component or
* will not exist (or be `false`).
*/
has: function (id) {
return !!this.__c[id];
},
/**@
* #.attr
* @comp Crafty Core
* @sign public this .attr(String property, * value)
* @param property - Property of the entity to modify
* @param value - Value to set the property to
* @sign public this .attr(Object map)
* @param map - Object where the key is the property to modify and the value as the property value
* @trigger Change - when properties change - {key: value}
*
* Use this method to set any property of the entity.
*
* @example
* ~~~
* this.attr({key: "value", prop: 5});
* this.key; //value
* this.prop; //5
*
* this.attr("key", "newvalue");
* this.key; //newvalue
* ~~~
*/
attr: function (key, value) {
if (arguments.length === 1) {
//if just the key, return the value
if (typeof key === "string") {
return this[key];
}
//extend if object
this.extend(key);
this.trigger("Change", key); //trigger change event
return this;
}
//if key value pair
this[key] = value;
var change = {};
change[key] = value;
this.trigger("Change", change); //trigger change event
return this;
},
/**@
* #.toArray
* @comp Crafty Core
* @sign public this .toArray(void)
*
* This method will simply return the found entities as an array.
*/
toArray: function () {
return slice.call(this, 0);
},
/**@
* #.timeout
* @comp Crafty Core
* @sign public this .timeout(Function callback, Number delay)
* @param callback - Method to execute after given amount of milliseconds
* @param delay - Amount of milliseconds to execute the method
*
* The delay method will execute a function after a given amount of time in milliseconds.
*
* Essentially a wrapper for `setTimeout`.
*
* @example
* Destroy itself after 100 milliseconds
* ~~~
* this.timeout(function() {
this.destroy();
* }, 100);
* ~~~
*/
timeout: function (callback, duration) {
this.each(function () {
var self = this;
setTimeout(function () {
callback.call(self);
}, duration);
});
return this;
},
/**@
* #.bind
* @comp Crafty Core
* @sign public this .bind(String eventName, Function callback)
* @param eventName - Name of the event to bind to
* @param callback - Method to execute when the event is triggered
* Attach the current entity (or entities) to listen for an event.
*
* Callback will be invoked when an event with the event name passed
* is triggered. Depending on the event, some data may be passed
* via an argument to the callback function.
*
* The first argument is the event name (can be anything) whilst the
* second argument is the callback. If the event has data, the
* callback should have an argument.
*
* Events are arbitrary and provide communication between components.
* You can trigger or bind an event even if it doesn't exist yet.
*
* Unlike DOM events, Crafty events are exectued synchronously.
*
* @example
* ~~~
* this.attr("triggers", 0); //set a trigger count
* this.bind("myevent", function() {
* this.triggers++; //whenever myevent is triggered, increment
* });
* this.bind("EnterFrame", function() {
* this.trigger("myevent"); //trigger myevent on every frame
* });
* ~~~
*
* @see .trigger, .unbind
*/
bind: function (event, callback) {
// (To learn how the handlers object works, see inline comment at Crafty.bind)
//optimization for 1 entity
if (this.length === 1) {
if (!handlers[event]) handlers[event] = {};
var h = handlers[event];
if (!h[this[0]]) h[this[0]] = []; //init handler array for entity
h[this[0]].push(callback); //add current callback
return this;
}
this.each(function () {
//init event collection
if (!handlers[event]) handlers[event] = {};
var h = handlers[event];
if (!h[this[0]]) h[this[0]] = []; //init handler array for entity
h[this[0]].push(callback); //add current callback
});
return this;
},
/**@
* #.unbind
* @comp Crafty Core
* @sign public this .unbind(String eventName[, Function callback])
* @param eventName - Name of the event to unbind
* @param callback - Function to unbind
* Removes binding with an event from current entity.
*
* Passing an event name will remove all events bound to
* that event. Passing a reference to the callback will
* unbind only that callback.
* @see .bind, .trigger
*/
unbind: function (event, callback) {
// (To learn how the handlers object works, see inline comment at Crafty.bind)
this.each(function () {
var hdl = handlers[event], i = 0, l, current;
//if no events, cancel
if (hdl && hdl[this[0]]) l = hdl[this[0]].length;
else return this;
//if no function, delete all
if (!callback) {
delete hdl[this[0]];
return this;
}
//look for a match if the function is passed
for (; i < l; i++) {
current = hdl[this[0]];
if (current[i] == callback) {
current.splice(i, 1);
i--;
}
}
});
return this;
},
/**@
* #.trigger
* @comp Crafty Core
* @sign public this .trigger(String eventName[, Object data])
* @param eventName - Event to trigger
* @param data - Arbitrary data that will be passed into every callback as an argument
* Trigger an event with arbitrary data. Will invoke all callbacks with
* the context (value of `this`) of the current entity object.
*
* *Note: This will only execute callbacks within the current entity, no other entity.*
*
* The first argument is the event name to trigger and the optional
* second argument is the arbitrary event data. This can be absolutely anything.
*
* Unlike DOM events, Crafty events are exectued synchronously.
*/
trigger: function (event, data) {
// (To learn how the handlers object works, see inline comment at Crafty.bind)
if (this.length === 1) {
//find the handlers assigned to the event and entity
if (handlers[event] && handlers[event][this[0]]) {
var callbacks = handlers[event][this[0]], i = 0, l = callbacks.length;
for (; i < l; i++) {
callbacks[i].call(this, data);
}
}
return this;
}
this.each(function () {
//find the handlers assigned to the event and entity
if (handlers[event] && handlers[event][this[0]]) {
var callbacks = handlers[event][this[0]], i = 0, l = callbacks.length;
for (; i < l; i++) {
callbacks[i].call(this, data);
}
}
});
return this;
},
/**@
* #.each
* @sign public this .each(Function method)
* @param method - Method to call on each iteration
* Iterates over found entities, calling a function for every entity.
*
* The function will be called for every entity and will pass the index
* in the iteration as an argument. The context (value of `this`) of the
* function will be the current entity in the iteration.
*
* @example
* Destroy every second 2D entity
* ~~~
* Crafty("2D").each(function(i) {
* if(i % 2 === 0) {
* this.destroy();
* }
* });
* ~~~
*/
each: function (func) {
var i = 0, l = this.length;
for (; i < l; i++) {
//skip if not exists
if (!entities[this[i]]) continue;
func.call(entities[this[i]], i);
}
return this;
},
/**@
* #.clone
* @comp Crafty Core
* @sign public Entity .clone(void)
* @returns Cloned entity of the current entity
*
* Method will create another entity with the exact same
* properties, components and methods as the current entity.
*/
clone: function () {
var comps = this.__c,
comp,
prop,
clone = Crafty.e();
for (comp in comps) {
clone.addComponent(comp);
}
for (prop in this) {
if (prop != "0" && prop != "_global" && prop != "_changed" && typeof this[prop] != "function" && typeof this[prop] != "object") {
clone[prop] = this[prop];
}
}
return clone;
},
/**@
* #.setter
* @comp Crafty Core
* @sign public this .setter(String property, Function callback)
* @param property - Property to watch for modification
* @param callback - Method to execute if the property is modified
* Will watch a property waiting for modification and will then invoke the
* given callback when attempting to modify.
*
* *Note: Support in IE<9 is slightly different. The method will be executed
* after the property has been set*
*/
setter: function (prop, callback) {
if (Crafty.support.setter) {
this.__defineSetter__(prop, callback);
} else if (Crafty.support.defineProperty) {
Object.defineProperty(this, prop, {
set: callback,
configurable: true
});
} else {
noSetter.push({
prop: prop,
obj: this,
fn: callback
});
}
return this;
},
/**@
* #.destroy
* @comp Crafty Core
* @sign public this .destroy(void)
* Will remove all event listeners and delete all properties as well as removing from the stage
*/
destroy: function () {
//remove all event handlers, delete from entities
this.each(function () {
this.trigger("Remove");
for (var e in handlers) {
this.unbind(e);
}
delete entities[this[0]];
});
}
};
//give the init instances the Crafty prototype
Crafty.fn.init.prototype = Crafty.fn;
/**
* Extension method to extend the namespace and
* selector instances
*/
Crafty.extend = Crafty.fn.extend = function (obj) {
var target = this, key;
//don't bother with nulls
if (!obj) return target;
for (key in obj) {
if (target === obj[key]) continue; //handle circular reference
target[key] = obj[key];
}
return target;
};
/**@
* #Crafty.extend
* @category Core
* Used to extend the Crafty namespace.
*/
Crafty.extend({
/**@
* #Crafty.init
* @category Core
* @trigger EnterFrame - on each frame - { frame: Number }
* @trigger Load - Just after the viewport is initialised. Before the EnterFrame loops is started
* @sign public this Crafty.init([Number width, Number height])
* @param width - Width of the stage
* @param height - Height of the stage
*
* Create a div with id `cr-stage`, if there is not already an HTMLElement with id `cr-stage` (by `Crafty.viewport.init`).
*
* Starts the `EnterFrame` interval. This will call the `EnterFrame` event for every frame.
*
* Can pass width and height values for the stage otherwise will default to window size (see `Crafty.DOM.window`).
*
* All `Load` events will be executed.
*
* Uses `requestAnimationFrame` to sync the drawing with the browser but will default to `setInterval` if the browser does not support it.
* @see Crafty.stop, Crafty.viewport
*/
init: function (w, h) {
Crafty.viewport.init(w, h);
//call all arbitrary functions attached to onload
this.trigger("Load");
this.timer.init();
return this;
},
/**@
* #.getVersion
* @comp Crafty Core
* @sign public this .getVersion()
* @returns Actually crafty version
*
* @example
* ~~~
* Crafty.getVersion(); //'0.5.2'
* ~~~
*/
getVersion: function () {
return '0.5.3';
},
/**@
* #Crafty.stop
* @category Core
* @trigger CraftyStop - when the game is stopped
* @sign public this Crafty.stop([bool clearState])
* @param clearState - if true the stage and all game state is cleared.
*
* Stops the EnterFrame interval and removes the stage element.
*
* To restart, use `Crafty.init()`.
* @see Crafty.init
*/
stop: function (clearState) {
this.timer.stop();
if (clearState) {
Crafty.audio.remove();
if (Crafty.stage && Crafty.stage.elem.parentNode) {
var newCrStage = document.createElement('div');
newCrStage.id = "cr-stage";
Crafty.stage.elem.parentNode.replaceChild(newCrStage, Crafty.stage.elem);
}
initState();
initComponents(Crafty, window, window.document);
}
Crafty.trigger("CraftyStop");
return this;
},
/**@
* #Crafty.pause
* @category Core
* @trigger Pause - when the game is paused
* @trigger Unpause - when the game is unpaused
* @sign public this Crafty.pause(void)
*
* Pauses the game by stopping the EnterFrame event from firing. If the game is already paused it is unpaused.
* You can pass a boolean parameter if you want to pause or unpause mo matter what the current state is.
* Modern browsers pauses the game when the page is not visible to the user. If you want the Pause event
* to be triggered when that happens you can enable autoPause in `Crafty.settings`.
*
* @example
* Have an entity pause the game when it is clicked.
* ~~~
* button.bind("click", function() {
* Crafty.pause();
* });
* ~~~
*/
pause: function (toggle) {
if (arguments.length == 1 ? toggle : !this._paused) {
this.trigger('Pause');
this._paused = true;
setTimeout(function(){ Crafty.timer.stop(); }, 0);
Crafty.keydown = {};
} else {
this.trigger('Unpause');
this._paused = false;
setTimeout(function(){ Crafty.timer.init(); }, 0);
}
return this;
},
/**@
* #Crafty.isPaused
* @category Core
* @sign public this Crafty.isPaused()
*
* Check whether the game is already paused or not.
*
* @example
* ~~~
* Crafty.isPaused();
* ~~~
*/
isPaused: function () {
return this._paused;
},
/**@
* #Crafty.timer
* @category Internal
* Handles game ticks
*/
timer: {
prev: (+new Date),
current: (+new Date),
currentTime: +new Date(),
frames:0,
frameTime:0,
init: function () {
var onFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
null;
if (onFrame) {
tick = function () {
Crafty.timer.step();
requestID = onFrame(tick);
//console.log(requestID + ', ' + frame)
}
tick();
} else {
tick = setInterval(function () { Crafty.timer.step(); }, 1000 / FPS);
}
},
stop: function () {
Crafty.trigger("CraftyStopTimer");
if (typeof tick === "number") clearInterval(tick);
var onFrame = window.cancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
null;
if (onFrame) onFrame(requestID);
tick = null;
},
/**@
* #Crafty.timer.step
* @comp Crafty.timer
* @sign public void Crafty.timer.step()
* Advances the game by triggering `EnterFrame` and calls `Crafty.DrawManager.draw` to update the stage.
*/
step: function () {
loops = 0;
this.currentTime = +new Date();
if (this.currentTime - nextGameTick > 60 * milliSecPerFrame) {
nextGameTick = this.currentTime - milliSecPerFrame;
}
while (this.currentTime > nextGameTick) {
Crafty.trigger("EnterFrame", { frame: frame++ });
nextGameTick += milliSecPerFrame;
loops++;
}
if (loops) {
Crafty.DrawManager.draw();
}
if(this.currentTime > this.frameTime){
Crafty.trigger("MessureFPS",{value:this.frame});
this.frame = 0;
this.frameTime = this.currentTime + 1000;
}else{
this.frame++;
}
},
/**@
* #Crafty.timer.getFPS
* @comp Crafty.timer
* @sign public void Crafty.timer.getFPS()
* Returns the target frames per second. This is not an actual frame rate.
*/
getFPS: function () {
return FPS;
},
/**@
* #Crafty.timer.simulateFrames
* @comp Crafty.timer
* Advances the game state by a number of frames and draws the resulting stage at the end. Useful for tests and debugging.
* @sign public this Crafty.timer.simulateFrames(Number frames)
* @param frames - number of frames to simulate
*/
simulateFrames: function (frames) {
while (frames-- > 0) {
Crafty.trigger("EnterFrame", { frame: frame++ });
}
Crafty.DrawManager.draw();
}
},
/**@
* #Crafty.addEntityFactory
* @category Core
* @param name - Name of the entity factory.
* @param callback - Function containing the entity creation procedure.
*
* Registers an Entity Factory. An Entity Factory allows for the repeatable creation of an Entity.
*
* @example
* ~~~
* Crafty.addEntityFactory('Projectile', function() {
* var entity = Crafty.e('2D, Canvas, Color, Physics, Collision')
* .color("red")
* .attr({
* w: 3,
* h: 3,
* x: this.x,
* y: this.y
* })