-
Notifications
You must be signed in to change notification settings - Fork 1
/
crafty.js
21350 lines (19667 loc) · 703 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.8.0
* http://craftyjs.com/
*
* Copyright 2018, Louis Stowasser
* Licensed under the MIT license.
*/
(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);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.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){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],2:[function(require,module,exports){
function createDeprecatedAlias(oldObject, oldName, newObject, newName) {
Object.defineProperty(oldObject, oldName, {
enumerable: false,
configurable: false,
get: function() { return newObject[newName]; },
set: function(value) { newObject[newName] = value; }
});
}
module.exports = {
defineAliases: function defineAliases(Crafty) {
createDeprecatedAlias(Crafty, "image_whitelist", Crafty, "imageWhitelist");
createDeprecatedAlias(Crafty, "mouseDispatch", Crafty.s('Mouse'), "processEvent");
createDeprecatedAlias(Crafty, "mouseButtonsDown", Crafty.s('Mouse'), "_buttonDown");
createDeprecatedAlias(Crafty, "lastEvent", Crafty.s('Mouse'), "lastMouseEvent");
createDeprecatedAlias(Crafty, "mouseObjs", Crafty.s('Mouse'), "mouseObjs");
createDeprecatedAlias(Crafty, "keyboardDispatch", Crafty.s('Keyboard'), "processEvent");
createDeprecatedAlias(Crafty, "keydown", Crafty.s('Keyboard'), "_keyDown");
createDeprecatedAlias(Crafty, "resetKeyDown", Crafty.s('Keyboard'), "resetKeyDown");
createDeprecatedAlias(Crafty, "touchDispatch", Crafty, "_touchDispatch");
createDeprecatedAlias(Crafty, "touchObjs", Crafty.s('Touch'), "touchObjs");
Crafty.touchHandler = {};
createDeprecatedAlias(Crafty.touchHandler, "fingers", Crafty.s('Touch'), "touchPoints");
}
};
},{}],3:[function(require,module,exports){
var Crafty = require("../core/core.js");
// ToggleInput contract
// Must provide an isDown method which returns whether the input is down or not
// May provide a destroy method which can be used for cleanup
// MouseButtonToggleInput
function MouseButtonToggleInput(button) {
this.button = button;
}
MouseButtonToggleInput.prototype = {
isDown: function() {
var mouseSystem = this.mouseSystem;
if (!mouseSystem) this.mouseSystem = mouseSystem = Crafty.s("Mouse");
return mouseSystem.isButtonDown(this.button);
}
};
// KeyboardToggleInput
function KeyboardToggleInput(key) {
this.key = key;
}
KeyboardToggleInput.prototype = {
isDown: function() {
var keyboardSystem = this.keyboardSystem;
if (!keyboardSystem)
this.keyboardSystem = keyboardSystem = Crafty.s("Keyboard");
return keyboardSystem.isKeyDown(this.key);
}
};
// ToggleInputGroup
function ToggleInputGroup(inputs) {
this.inputs = inputs;
}
// Handles a group of inputs that represent the same toggle state
ToggleInputGroup.prototype = {
timeDown: null,
isActive: function() {
for (var i in this.inputs) {
var input = this.inputs[i];
if (input.isDown()) {
if (!this.timeDown) {
this.timeDown = Date.now();
}
return true;
}
}
delete this.timeDown;
return false;
},
destroy: function() {
for (var i in this.inputs) {
if (typeof this.inputs[i].destroy === "function") {
this.inputs[i].destroy();
}
}
}
};
// Provides abstractions for specific types of inputs:
// - DirectionalInput: {x, y}
// - TriggerInputDown/TriggerInputUp
/**@
* #Controls
* @category Controls
* @kind System
*
* A built-in system for linking specific inputs to general types of input events.
*
* @note The methods provided by this system are likely to change in future verisons of Crafty, as more input types are supported.
*
* @trigger TriggerInputDown - When a trigger group is activated - {name}
* @trigger TriggerInputUp - When a trigger group is released - {name, downFor}
* @trigger DirectionalInput - When a directional input changes - {name, x, y}
*
* @trigger ControlDefined - When a control input is defined - {type, name}
* @trigger ControlDestroyed - When a control input is destroyed - {type, name}
*/
Crafty.s("Controls", {
init: function() {
// internal object to store definitions
this._dpads = {};
this._triggers = {};
// listen to mouse events
Crafty.s("Mouse").bind("MouseDown", this.updateTriggers.bind(this));
Crafty.s("Mouse").bind("MouseUp", this.updateTriggers.bind(this));
Crafty.s("Mouse").bind("DoubleClick", this.updateTriggers.bind(this));
Crafty.s("Mouse").bind("Click", this.updateTriggers.bind(this));
},
events: {
EnterFrame: "runEvents",
KeyDown: "updateTriggers",
KeyUp: "updateTriggers"
},
// Runs through all triggers and updates their status
updateTriggers: function(e) {
for (var t in this._triggers) {
var trigger = this._triggers[t];
this.updateTriggerInput(trigger);
}
},
runEvents: function() {
// Trigger DirectionalInput events for dpads
for (var d in this._dpads) {
var dpad = this._dpads[d];
dpad.oldX = dpad.x;
dpad.oldY = dpad.y;
this.updateDpadInput(dpad, dpad.multipleDirectionBehavior);
this.updateActiveDirection(dpad, dpad.normalize);
dpad.event.x = dpad.x;
dpad.event.y = dpad.y;
if (dpad.x !== dpad.oldX || dpad.y !== dpad.oldY) {
Crafty.trigger("DirectionalInput", dpad.event);
}
}
},
getDpad: function(name) {
return this._dpads[name];
},
isTriggerDown: function(name) {
return this._triggers[name].active;
},
/**@
* #.defineTriggerGroup
* @comp Controls
* @kind Method
*
* @sign defineTriggerGroup(string name, obj definition)
* @param name - a name for the trigger group
* @param definition - an object which defines the inputs for the trigger
*
* A trigger group is a set of togglable inputs mapped to the same event.
* If any of the inputs are down, the trigger is considered down. If all are up, it is considered up.
* When the trigger state changes, a `TriggerInputUp` or `TriggerInputDown` event is fired.
*
* The definition object lists the inputs that are mapped to the trigger:
* - `keys`: An array of Crafty keycodes
* - `mouseButtons`: An array of Crafty mouse button codes
*
* @example
* ~~~
* // Define a trigger group mapped to the left mouse button and the A and B keys.
* Crafty.s("Controls").defineTriggerGroup("MyTrigger", {
* mouseButtons: [Crafty.mouseButtons.LEFT],
* keys: [Crafty.keys.A, Crafty.keys.B]
* });
* ~~~
*
* @see .destroyTriggerGroup
* @see Crafty.mouseButtons
* @see Crafty.keys
* @see Controllable
*/
defineTriggerGroup: function(name, definition) {
var inputs;
if (Array.isArray(definition)) {
inputs = definition;
} else {
inputs = [];
if (definition.mouseButtons) {
for (var b in definition.mouseButtons) {
inputs.push(
new MouseButtonToggleInput(definition.mouseButtons[b])
);
}
}
if (definition.keys) {
for (var k in definition.keys) {
inputs.push(new KeyboardToggleInput(definition.keys[k]));
}
}
}
this.destroyTriggerGroup(name);
this._triggers[name] = {
name: name,
input: new ToggleInputGroup(inputs),
downFor: 0,
active: false
};
Crafty.trigger("ControlDefined", { type: "TriggerGroup", name: name });
},
/**@
* #.destroyTriggerGroup
* @comp Controls
* @kind Method
*
* @sign destroyTriggerGroup(string name)
* @param name - the name of the trigger group
*
* Destroys a previously defined trigger group.
*
* @see .defineTriggerGroup
*/
destroyTriggerGroup: function(name) {
if (this._triggers[name]) {
this._triggers[name].input.destroy();
delete this._triggers[name];
Crafty.trigger("ControlDestroyed", {
type: "TriggerGroup",
name: name
});
}
},
/**@
* #.defineDpad
* @comp Controls
* @kind Method
*
* @sign defineDpad(string name, obj definition[, obj options])
* @param name - a name for the dpad input
* @param definition - an object which defines the inputs and directions for the dpad
* @param options - a set of options for the dpad
*
* A dpad is a type of directional control which maps a set of triggers to a set of directions.
*
* The options object has two properties:
* - `normalize` *(bool)*: If true, the directional input will be normalized to a unit vector. Defaults to false.
* - `multipleDirectionBehavior` *(string)*: How to behave when multiple directions are active at the same time. Values are "first", "last", and "all". Defaults to "all".
*
* @example
* ~~~
* // Define a two-direction dpad, with two keys each bound to the right and left directions
* Crafty.s("Controls").defineDpad("MyDpad", {RIGHT_ARROW: 0, LEFT_ARROW: 180, D: 0, A: 180});
* ~~~
*
* @see .destroyDpad
* @see Crafty.keys
* @see Controllable
* @see Multiway
*/
defineDpad: function(name, definition, options) {
var directionDict = {};
for (var k in definition) {
var direction = definition[k];
var keyCode = Crafty.keys[k] || k;
// create a mapping of directions to all associated keycodes
if (!directionDict[direction]) {
directionDict[direction] = [];
}
directionDict[direction].push(new KeyboardToggleInput(keyCode));
}
// Create a useful definition from the input format that tracks state
var parsedDefinition = {};
for (var d in directionDict) {
parsedDefinition[d] = {
input: new ToggleInputGroup(directionDict[d]),
active: false,
n: this.parseDirection(d)
};
}
if (typeof options === "undefined") {
options = {};
}
if (typeof options.normalize === "undefined") {
options.normalize = false;
}
if (typeof options.multipleDirectionBehavior === "undefined") {
options.multipleDirectionBehavior = "all";
}
// Create the fully realized dpad object
// Store the name/definition pair
this.destroyDpad(name);
this._dpads[name] = {
name: name,
directions: parsedDefinition,
x: 0,
y: 0,
oldX: 0,
oldY: 0,
event: { x: 0, y: 0, name: name },
normalize: options.normalize,
multipleDirectionBehavior: options.multipleDirectionBehavior
};
Crafty.trigger("ControlDefined", { type: "Dpad", name: name });
},
/**@
* #.destroyDpad
* @comp Controls
* @kind Method
*
* @sign destroyDpad(string name)
* @param name - the name of the dpad input
*
* Destroys a previously defined dpad.
*
* @see .defineDpad
*/
destroyDpad: function(name) {
if (this._dpads[name]) {
for (var d in this._dpads[name].parsedDefinition) {
this._dpads[name].parsedDefinition[d].input.destroy();
}
delete this._dpads[name];
Crafty.trigger("ControlDestroyed", { type: "Dpad", name: name });
}
},
// Takes an amount in degrees and converts it to an x/y object.
// Clamps to avoid rounding issues with sin/cos
parseDirection: function(direction) {
return {
x: Math.round(Math.cos(direction * (Math.PI / 180)) * 1000) / 1000,
y: Math.round(Math.sin(direction * (Math.PI / 180)) * 1000) / 1000
};
},
// dpad definition is a map of directions to keys array and active flag
updateActiveDirection: function(dpad, normalize) {
var x = 0,
y = 0;
// Sum up all active directions
for (var d in dpad.directions) {
var dir = dpad.directions[d];
if (!dir.active) continue;
x += dir.n.x;
y += dir.n.y;
}
// Mitigate rounding errors when close to zero movement
x = -1e-10 < x && x < 1e-10 ? 0 : x;
y = -1e-10 < y && y < 1e-10 ? 0 : y;
// Normalize
if (normalize) {
var m = Math.sqrt(x * x + y * y);
if (m > 0) {
x /= m;
y /= m;
}
}
dpad.x = x;
dpad.y = y;
},
updateTriggerInput: function(trigger) {
if (!trigger.active) {
if (trigger.input.isActive()) {
trigger.downFor = Date.now() - trigger.input.timeDown;
trigger.active = true;
Crafty.trigger("TriggerInputDown", trigger);
}
} else {
if (!trigger.input.isActive()) {
trigger.active = false;
Crafty.trigger("TriggerInputUp", trigger);
trigger.downFor = 0;
}
}
},
// Has to handle three cases concerning multiple active input groups:
// - "all": all directions are active
// - "last": one direction at a time, new directions replace old ones
// - "first": one direction at a time, new directions are ignored while old ones are still active
updateDpadInput: function(dpad, multiBehavior) {
var d, dir;
var winner;
for (d in dpad.directions) {
dir = dpad.directions[d];
dir.active = false;
if (dir.input.isActive()) {
if (multiBehavior === "all") {
dir.active = true;
} else {
if (!winner) {
winner = dir;
} else {
if (multiBehavior === "first") {
if (winner.input.timeDown > dir.input.timeDown) {
winner = dir;
}
}
if (multiBehavior === "last") {
if (winner.input.timeDown < dir.input.timeDown) {
winner = dir;
}
}
}
}
}
}
// If we picked a winner, set it active
if (winner) winner.active = true;
}
});
},{"../core/core.js":10}],4:[function(require,module,exports){
var Crafty = require("../core/core.js");
/**@
* #Draggable
* @category Controls
* @kind Component
* Enable drag and drop of the entity. Listens to events from `MouseDrag` and moves entity accordingly.
*
* @see MouseDrag
*/
Crafty.c("Draggable", {
_origX: null,
_origY: null,
_oldX: null,
_oldY: null,
_dir: null,
required: "MouseDrag",
events: {
StartDrag: "_startDrag",
Dragging: "_drag"
},
/**@
* #.enableDrag
* @comp Draggable
* @kind Method
*
* @sign public this .enableDrag(void)
*
* Reenable dragging of entity. Use if `.disableDrag` has been called.
*
* @see .disableDrag
*/
enableDrag: function() {
this.uniqueBind("Dragging", this._drag);
return this;
},
/**@
* #.disableDrag
* @comp Draggable
* @kind Method
*
* @sign public this .disableDrag(void)
*
* Disables entity dragging. Reenable with `.enableDrag()`.
*
* @see .enableDrag
*/
disableDrag: function() {
this.unbind("Dragging", this._drag);
return this;
},
/**@
* #.dragDirection
* @comp Draggable
* @kind Method
*
* Method used for modifying the drag direction.
* If direction is set, the entity being dragged will only move along the specified direction.
* If direction is not set, the entity being dragged will move along any direction.
*
* @sign public this .dragDirection()
* Remove any previously specified direction.
*
* @sign public this .dragDirection(vector)
* @param vector - Of the form of {x: valx, y: valy}, the vector (valx, valy) denotes the move direction.
*
* @sign public this .dragDirection(degree)
* @param degree - A number, the degree (clockwise) of the move direction with respect to the x axis.
*
* Specify the dragging direction.
*
* @example
* ~~~
* this.dragDirection()
* this.dragDirection({x:1, y:0}) //Horizontal
* this.dragDirection({x:0, y:1}) //Vertical
* // Note: because of the orientation of x and y axis,
* // this is 45 degree clockwise with respect to the x axis.
* this.dragDirection({x:1, y:1}) //45 degree.
* this.dragDirection(60) //60 degree.
* ~~~
*/
dragDirection: function(dir) {
if (typeof dir === "undefined") {
this._dir = null;
} else if (+dir === dir) {
//dir is a number
this._dir = {
x: Math.cos((dir / 180) * Math.PI),
y: Math.sin((dir / 180) * Math.PI)
};
} else {
if (dir.x === 0 && dir.y === 0) {
this._dir = { x: 0, y: 0 };
} else {
var r = Math.sqrt(dir.x * dir.x + dir.y * dir.y);
this._dir = {
x: dir.x / r,
y: dir.y / r
};
}
}
return this;
},
_startDrag: function(e) {
this._origX = e.realX;
this._origY = e.realY;
this._oldX = this._x;
this._oldY = this._y;
},
//Note: the code is not tested with zoom, etc., that may distort the direction between the viewport and the coordinate on the canvas.
_drag: function(e) {
if (this._dir) {
if (this._dir.x !== 0 || this._dir.y !== 0) {
var len =
(e.realX - this._origX) * this._dir.x +
(e.realY - this._origY) * this._dir.y;
this.x = this._oldX + len * this._dir.x;
this.y = this._oldY + len * this._dir.y;
}
} else {
this.x = this._oldX + (e.realX - this._origX);
this.y = this._oldY + (e.realY - this._origY);
}
}
});
/**@
* #Controllable
* @category Controls
* @kind Component
*
* Used to bind methods to generalized input events.
*
* Currently supports the events "DirectionalInput", "TriggerInputDown", and "TriggerInputUp".
*
*/
Crafty.c("Controllable", {
init: function() {
this._inputBindings = {
DirectionalInput: {},
TriggerInputDown: {},
TriggerInputUp: {}
};
},
events: {
// We don't want to use dot notation here for the property names
/* jshint -W069 */
DirectionalInput: function(e) {
if (this._inputBindings["DirectionalInput"][e.name]) {
this._inputBindings["DirectionalInput"][e.name].call(this, e);
}
},
TriggerInputDown: function(e) {
if (this._inputBindings["TriggerInputDown"][e.name]) {
this._inputBindings["TriggerInputDown"][e.name].call(this, e);
}
},
TriggerInputUp: function(e) {
if (this._inputBindings["TriggerInputUp"][e.name]) {
this._inputBindings["TriggerInputUp"][e.name].call(this, e);
}
}
/* jshint +W069 */
},
/**@
* #.linkInput
* @comp Controllable
* @kind Method
*
* @sign public this linkInput(string event, string name, function fn)
* @param event - the name of the input event
* @param name - the name of the input
* @param fn - the function that will be called with the event object
*
* Binds the function to the particular named event trigger.
*
* Currently supports three types of input events. Each event will have a `name` property.
* - `DirectionalInput`: The event will have `x` and `y` properties representing the directional input vector, often normalized to a unit vector. Triggered when the input changes.
* - `TriggerInputDown`: Occurs when the input is triggered.
* - `TriggerInputDown`: Occurs when the trigger is released. The event will have a `downFor` property, indicating how long it had been active.
*
* @example
* ~~~~
* // Create a trigger bound to the `b` key
* Crafty.s("Controls").defineTriggerGroup("BlushTrigger", {keys:['b']});
* // Create a blue square that turns pink when the trigger is pressed
* Crafty.e("2D, Canvas, Color, Controllable")
* .attr({x:10, y:10, h:10, w:10}).color("blue")
* .linkInput("TriggerInputDown", "BlushTrigger", function(){this.color('pink');});
* ~~~
*
* @see .unlinkInput
*/
linkInput: function(event, name, fn) {
this._inputBindings[event][name] = fn;
return this;
},
/**@
* #.unlinkInput
* @comp Controllable
* @kind Method
*
* @sign public this linkInput(string event, string name)
* @param event - the name of the input event
* @param name - the name of the input
*
* Removes a binding setup by linkInput
*
* @see .linkInput
*/
unlinkInput: function(event, name) {
delete this._inputBindings[event][name];
return this;
},
disableControls: false,
/**@
* #.enableControl
* @comp Controllable
* @kind Method
*
* @sign public this .enableControl()
*
* Enable the component to listen to input events.
*
* @example
* ~~~
* this.enableControl();
* ~~~
*/
enableControl: function() {
this.disableControls = false;
return this;
},
/**@
* #.disableControl
* @comp Controllable
* @kind Method
*
* @sign public this .disableControl()
*
* Disable the component from responding to input events.
*
* @example
* ~~~
* this.disableControl();
* ~~~
*/
disableControl: function() {
this.disableControls = true;
return this;
}
});
/**@
* #Multiway
* @category Controls
* @kind Component
*
* Used to bind keys to directions and have the entity move accordingly.
*
* Multiway acts by listening to directional events, and then setting the velocity each frame based on the current direction and the current speed.
*
* If a speed is not defined for a particular axis (x or y), then the velocity along that axis will not be set.
*
* This behavior works in most cases, but can cause undesired behavior if you manipulate velocities by yourself while this component is in effect.
* If you need to resolve collisions, it's advised to correct the position directly rather than to manipulate the velocity.
* If you still need to reset the velocity once a collision happens, make sure to re-add the previous velocity once the collision is resolved.
*
* Additionally, this component provides the entity with `Motion` methods & events.
*
* @see Motion
*/
Crafty.c("Multiway", {
_speed: null,
init: function() {
this.requires("Motion, Controllable");
this._dpadName = "MultiwayDpad" + this[0];
this._speed = { x: 150, y: 150 };
this._direction = { x: 0, y: 0 };
},
remove: function() {
if (!this.disableControls) this.vx = this.vy = 0;
this.unlinkInput("DirectionalInput", this._dpadName);
Crafty.s("Controls").destroyDpad(this._dpadName);
},
events: {
UpdateFrame: function() {
if (!this.disableControls) {
if (
typeof this._speed.x !== "undefined" &&
this._speed.x !== null
) {
this.vx = this._speed.x * this._direction.x;
}
if (
typeof this._speed.y !== "undefined" &&
this._speed.y !== null
) {
this.vy = this._speed.y * this._direction.y;
}
}
}
},
// Rather than update the velocity directly in response to changing input, track the input direction separately
// That makes it easier to enable/disable control
_updateDirection: function(e) {
this._direction.x = e.x;
this._direction.y = e.y;
},
/**@
* #.multiway
* @comp Multiway
* @kind Method
*
* @sign public this .multiway([Number speed,] Object keyBindings[, Object options])
* @param speed - A speed in pixels per second
* @param keyBindings - What keys should make the entity go in which direction. Direction is specified in degrees
* @param options - An object with options for `normalize` and `multipleDirectionBehavior`.
*
* Constructor to initialize the speed and keyBindings.
* Component will listen to key events and move the entity appropriately.
* Can be called while a key is pressed to change direction & speed on the fly.
*
* The options parameter controls the behavior of the component, and has the following defaults:
*
* - `"normalize": false`. When set to true, the directional input always has a magnitude of 1
* - `"multipleDirectionBehavior": "all"` How to resolve multiple active directions.
* Set to "first" or "last" to allow only one active direction at a time.
*
* @example
* ~~~
* this.multiway(150, {UP_ARROW: -90, DOWN_ARROW: 90, RIGHT_ARROW: 0, LEFT_ARROW: 180});
* this.multiway({x:150,y:75}, {UP_ARROW: -90, DOWN_ARROW: 90, RIGHT_ARROW: 0, LEFT_ARROW: 180});
* this.multiway({W: -90, S: 90, D: 0, A: 180});
* ~~~
*
* @see Crafty.keys
*/
multiway: function(speed, keys, options) {
var inputSystem = Crafty.s("Controls");
if (keys) {
this.speed(speed);
} else {
keys = speed;