-
Notifications
You must be signed in to change notification settings - Fork 84
/
plugins.js
5376 lines (4418 loc) · 168 KB
/
plugins.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
// player.vy = 0;
// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level SIMPLE_OPTIMIZATIONS
// @language ECMASCRIPT5
// @fileoverview
// @suppress {checkTypes | globalThis | checkVars}
// ==/ClosureCompiler==
/*
Ga plugins
==========
Weclome to the `plugins.js` file!
This file contains lots of extra tools that are really useful for making games,
but which are more specialized that than the universal tools in `ga.js` file.
How can use these plugins? The easiest way is just to link this entire file
with a `<script>` tag. Then you have immediate access to all this code
and you can decide later what you really need.
Your own custom plugins
-----------------------
If you wan to keep you game file size small, create
your own custom plugins file. Here's how:
1. Make a new JS file called `custom.js` (or an other name you want to give it.)
2. Add this:
GA.custom = function(ga) {
//Your own collection of plugins will go here
};
3. Link `custom.js` to your game's main HTML document with a `<script>` tag.
4. Then just copy/paste any plugin functions from this
file (`plugins.js`) into your own `custom.js` file. Like this:
GA.custom = function(ga) {
//Create a random number within a specific range
ga.randomInt = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
};
The `GA.custom` function is called by Ga as soon as the engine has
finished initializing, but before the game runs. This means you
can use it to run any other custom setup task that you want to
perform before any of the game code runs. You could also use the
`GA.custom` function to overwrite any of Ga's default properties
with your own. Go wild!
The plugins in this file
------------------------
The code in this `plugins.js` file is organized into chapters.
Use your text editor's search features to find what you're looking for.
Here's the table of contents to get you started:
### Prologue: Polyfills
- Necessary polyfills for some of the API's used in this file.
### Chapter 1: Utilities
`move`: Make a sprite or group move (or an array of them) by updating its velocity.
`distance`: The distance in pixels between the center point of two sprites.
`followEase`: Make a sprite ease to the position of another sprite.
`easeProperty`: Ease a single sprite property to another value.
`slide`: Ease a sprite to a specific position.
`fadeIn`: Fade in a sprite.
`fadeOut`: Fade out a sprite.
`fade`: Fades in or out.
`pulse`: Uses the `fade` method to make a sprite's alpha oscillate.
`follow`: Make a sprite follow another sprite at a fixed speed.
`rotateSprite`: Make a sprite rotate around the center of another sprite.
`rotatePoint`: Make any x/y point rotate around any other point.
`angle`: Get the angle between the center points of two sprites
`randomInt`: Generate a random integer within a range.
`randomFloat`: Generate a random floating point number within a range.
`wait`: Wait for a certain number of milliseconds and then execute a callback function.
`worldCamera`: A method that creates and returns a camera for a scrolling game world.
`scaleToWindow`: Automatically scales and centers the game to the maximum browser window area.
`shake`: Make a sprite or group shake. You can use it for a screen shake effect.
### Chapter 2: The tweening module
`tweens`: An array to store all of Ga's current tweens.
`updateTweens`: A function that updates all the tweens each frame inside Ga's game loop.
`ease`: An object that stores references to useful easing functions.
`tweenProperty`: A generic low-level method that tweens any sprite property.
`slide`: Make a sprite slide from one x/y position to another.
`fadeIn`: Fade a sprite in.
`fadeOut`: Fade a sprite out.
`pulse`: Make a sprite fade in and out in a loop.
`makeTween`: A low-level function to help construct complex tweens.
`scale`: Smoothly change the scale of a sprite.
`breathe`: A breathing effect that changes the sprite's scale in a continuous loop.
`strobe`: A psychedelic flashing scale effect.
`wobble`: Make a sprite wobble like a plate of jelly.
`removeTween`: A universal method for remove a tween from Ga's engine.
`followCurve`: Make a sprite follow a bezier curve that you can specify.
`followPath`: Make a sprite follow a path of connected waypoints.
`walkCurve`: Make a sprite follow a path of connected curves.
### Chapter 3: Sprite creation tools
`shoot`: A function for making sprites shoot bullets.
`grid`: Easily plot a grid of sprites. Returns a container full of sprite `children`.
`progressBar`: A loading progress bar you can use to display while game assets are loading.`
`particleEffect`: A versatile function for creating particles.
`emitter`: A particle emitter for creating a constant stream of particles.
`tilingSprite`: An easy way to create a seamless scrolling background effect.
`burst`: DEPRICATED. A particle explosion effect.
### Chapter 4: Collision
#### Boundary collisions
`outsideBounds`: Tells you if a sprite has exceeded the boundary of another sprite or container.
`contain`: Contains a sprite inside another sprite. Optional bounce if the sprite hits the edges.
#### Shape collisions
`hitTestPoint`: Returns `true` or `false` if an x/y point is intersecting a rectangle or circle.
`hitTestCircle`: Returns `true` if any two circular sprites overlap.
`hitTestRectangle`: Returns `true` if any two rectangular sprites overlap.
`hitTestCircleRectangle`: Returns `true` if rectangular and circular sprites overlap.
`hitTestCirclePoint`: Returns `true` if a point intersects a circle.
`rectangleCollision`: Prevents two colliding rectangles from overlapping and tells you the collision side
`circleCollision`: Makes a moving circle bounce away from a stationary circle.
`movingCircleCollision`: Makes two moving circles bounce apart.
`multipleCircleCollision`: Bounce apart any two circles that are in the same array.
`bounceOffSurface`: A helper method that's use internally by these collision functions.
#### 2D tile-based collision utilities
`getIndex`: Converts a sprite's x/y pixel coordinates into an array index number.
`getTile`: Converts a sprite's index number into x/y pixel coordinates.
`surroundingCells`: returns an array of 9 index numbers of cells surrounding a center cell.
`getPoints`: returns an object with the x/y positions of all the sprite's corner points.
`hitTestTile`: A versatile collision detection function for tile based games.
`updateMap`: Returns a new map array with the new index positions of sprites.
### Chapter 5: Sprite controllers
`keyControlFourWay`: Assign keyboard keys to make a sprite move at a fixed speed in 4 directions
### Chapter 6: Tiled editor importers
`makeTiledWorld`: Creates a game world using Tiled Editor's JSON export data.
### Chapter 7: The fullscreen module
`requestFullscreen`: Used by `enableFullscreen` to launch fullscreen mode.
`exitFullscreen`: used by `enableFullscreen` to exit fullsrcreen mode.
`alignFullscreen`: Used by `enableFullscreen` to scale and center the canvas in fullscreen mode.
`enableFullscreen`: Enables fullscreen mode when the user clicks or touches the canvas.
### Chapter 8: Sound
`ga.actx`: The audio context.
`makeSound`: a method for loading and controling sound files.
`sound`: a method that returns a sound file object.
`soundEffect`: a versatile method for generating sound effects from pure code.
`impulseResponse`: A helper method for adding reverb to sounds.
*/
/*
Prologue
--------
Some necessary polyfills for some of the newer APIs used in this file
*/
/*
### Fixing the WebAudio API.
The WebAudio API is so new that it's API is not consistently implemented properly across
all modern browsers. Thankfully, Chris Wilson's Audio Context Monkey Patch script
normalizes the API for maximum compatibility.
https://github.com/cwilso/AudioContext-MonkeyPatch/blob/gh-pages/AudioContextMonkeyPatch.js
It's included here.
Thank you, Chris!
*/
(function (global, exports, perf) {
'use strict';
function fixSetTarget(param) {
if (!param) // if NYI, just return
return;
if (!param.setTargetAtTime)
param.setTargetAtTime = param.setTargetValueAtTime;
}
if (window.hasOwnProperty('webkitAudioContext') &&
!window.hasOwnProperty('AudioContext')) {
window.AudioContext = webkitAudioContext;
if (!AudioContext.prototype.hasOwnProperty('createGain'))
AudioContext.prototype.createGain = AudioContext.prototype.createGainNode;
if (!AudioContext.prototype.hasOwnProperty('createDelay'))
AudioContext.prototype.createDelay = AudioContext.prototype.createDelayNode;
if (!AudioContext.prototype.hasOwnProperty('createScriptProcessor'))
AudioContext.prototype.createScriptProcessor = AudioContext.prototype.createJavaScriptNode;
AudioContext.prototype.internal_createGain = AudioContext.prototype.createGain;
AudioContext.prototype.createGain = function() {
var node = this.internal_createGain();
fixSetTarget(node.gain);
return node;
};
AudioContext.prototype.internal_createDelay = AudioContext.prototype.createDelay;
AudioContext.prototype.createDelay = function(maxDelayTime) {
var node = maxDelayTime ? this.internal_createDelay(maxDelayTime) : this.internal_createDelay();
fixSetTarget(node.delayTime);
return node;
};
AudioContext.prototype.internal_createBufferSource = AudioContext.prototype.createBufferSource;
AudioContext.prototype.createBufferSource = function() {
var node = this.internal_createBufferSource();
if (!node.start) {
node.start = function ( when, offset, duration ) {
if ( offset || duration )
this.noteGrainOn( when, offset, duration );
else
this.noteOn( when );
}
}
if (!node.stop)
node.stop = node.noteOff;
fixSetTarget(node.playbackRate);
return node;
};
AudioContext.prototype.internal_createDynamicsCompressor = AudioContext.prototype.createDynamicsCompressor;
AudioContext.prototype.createDynamicsCompressor = function() {
var node = this.internal_createDynamicsCompressor();
fixSetTarget(node.threshold);
fixSetTarget(node.knee);
fixSetTarget(node.ratio);
fixSetTarget(node.reduction);
fixSetTarget(node.attack);
fixSetTarget(node.release);
return node;
};
AudioContext.prototype.internal_createBiquadFilter = AudioContext.prototype.createBiquadFilter;
AudioContext.prototype.createBiquadFilter = function() {
var node = this.internal_createBiquadFilter();
fixSetTarget(node.frequency);
fixSetTarget(node.detune);
fixSetTarget(node.Q);
fixSetTarget(node.gain);
return node;
};
if (AudioContext.prototype.hasOwnProperty( 'createOscillator' )) {
AudioContext.prototype.internal_createOscillator = AudioContext.prototype.createOscillator;
AudioContext.prototype.createOscillator = function() {
var node = this.internal_createOscillator();
if (!node.start)
node.start = node.noteOn;
if (!node.stop)
node.stop = node.noteOff;
fixSetTarget(node.frequency);
fixSetTarget(node.detune);
return node;
};
}
}
}(window));
//### Fixing the Fullscreen API.
//The Fullscreen API is also in flux and has a quirky browser
//implementations. Here's a fix for it, thanks to Norman Paschke:
//https://github.com/neovov/Fullscreen-API-Polyfill/blob/master/fullscreen-api-polyfill.js
(function (doc) {
// Use JavaScript script mode
"use strict";
/*global Element */
var pollute = true,
api,
vendor,
apis = {
// http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
w3: {
enabled: "fullscreenEnabled",
element: "fullscreenElement",
request: "requestFullscreen",
exit: "exitFullscreen",
events: {
change: "fullscreenchange",
error: "fullscreenerror"
}
},
webkit: {
enabled: "webkitIsFullScreen",
element: "webkitCurrentFullScreenElement",
request: "webkitRequestFullScreen",
exit: "webkitCancelFullScreen",
events: {
change: "webkitfullscreenchange",
error: "webkitfullscreenerror"
}
},
moz: {
enabled: "mozFullScreen",
element: "mozFullScreenElement",
request: "mozRequestFullScreen",
exit: "mozCancelFullScreen",
events: {
change: "mozfullscreenchange",
error: "mozfullscreenerror"
}
},
ms: {
enabled: "msFullscreenEnabled",
element: "msFullscreenElement",
request: "msRequestFullscreen",
exit: "msExitFullscreen",
events: {
change: "MSFullscreenChange",
error: "MSFullscreenError"
}
}
},
w3 = apis.w3;
// Loop through each vendor's specific API
for (vendor in apis) {
// Check if document has the "enabled" property
if (apis[vendor].enabled in doc) {
// It seems this browser support the fullscreen API
api = apis[vendor];
break;
}
}
function dispatch( type, target ) {
var event = doc.createEvent( "Event" );
event.initEvent( type, true, false );
target.dispatchEvent( event );
} // end of dispatch()
function handleChange( e ) {
// Recopy the enabled and element values
doc[w3.enabled] = doc[api.enabled];
doc[w3.element] = doc[api.element];
dispatch( w3.events.change, e.target );
} // end of handleChange()
function handleError( e ) {
dispatch( w3.events.error, e.target );
} // end of handleError()
// Pollute only if the API doesn't already exists
if (pollute && !(w3.enabled in doc) && api) {
// Add listeners for fullscreen events
doc.addEventListener( api.events.change, handleChange, false );
doc.addEventListener( api.events.error, handleError, false );
// Copy the default value
doc[w3.enabled] = doc[api.enabled];
doc[w3.element] = doc[api.element];
// Match the reference for exitFullscreen
doc[w3.exit] = doc[api.exit];
// Add the request method to the Element's prototype
Element.prototype[w3.request] = function () {
return this[api.request].apply( this, arguments );
};
}
// Return the API found (or undefined if the Fullscreen API is unavailable)
return api;
}(document));
GA = GA || {};
GA.plugins = function(ga) {
/*
Chapter 1: Utilities
--------------------
*/
//### move
//Move a sprite or an array of sprites by adding its
//velocity to its position
ga.move = function(sprites) {
if (sprites instanceof Array === false) {
internal_move(sprites)
} else {
for (var i = 0; i < sprites.length; i++) {
internal_move(sprites[i])
}
}
};
function internal_move(sprite) {
sprite.x += sprite.vx | 0;
sprite.y += sprite.vy | 0;
}
/*
### distance
Find the distance in pixels between two sprites.
Parameters:
a. A sprite object with `centerX` and `centerX` properties.
b. A sprite object with `centerY` and `centerY` properties.
The function returns the number of pixels distance between the sprites.
*/
ga.distance = function (s1, s2) {
var vx = s2.centerX - s1.centerX,
vy = s2.centerY - s1.centerY;
return Math.sqrt(vx * vx + vy * vy);
};
/*
### followEase
Make a sprite ease to the position of another sprite.
Parameters:
a. A sprite object with `centerX` and `centerY` properties. This is the `follower`
sprite.
b. A sprite object with `centerX` and `centerY` properties. This is the `leader` sprite that
the follower will chase
c. The easing value, such as 0.3. A higher number makes the follower move faster
*/
ga.followEase = function(follower, leader, speed) {
//Figure out the distance between the sprites
var vx = leader.centerX - follower.centerX,
vy = leader.centerY - follower.centerY,
distance = Math.sqrt(vx * vx + vy * vy);
//Move the follower if it's more than 1 pixel
//away from the leader
if (distance >= 1) {
follower.x += vx * speed;
follower.y += vy * speed;
}
};
/*
### followConstant
Make a sprite move towards another sprite at a regular speed.
Parameters:
a. A sprite object with `centerX` and `centerY` properties. This is the `follower`
sprite.
b. A sprite object with `centerX` and `centerY` properties. This is the `leader` sprite that
the follower will chase
c. The speed value, such as 3. The is the pixels per frame that the sprite will move. A higher number makes the follower move faster.
*/
ga.followConstant = function(follower, leader, speed) {
//Figure out the distance between the sprites
var vx = leader.centerX - follower.centerX,
vy = leader.centerY - follower.centerY,
distance = Math.sqrt(vx * vx + vy * vy);
//Move the follower if it's more than 1 move
//away from the leader
if (distance >= speed) {
follower.x += (vx / distance) * speed;
follower.y += (vy / distance) * speed;
}
};
//### rotateAroundSprite
//Make a sprite rotate around another sprite
ga.rotateAroundSprite = function(rotatingSprite, centerSprite, distance, angle) {
rotatingSprite.x
= centerSprite.centerX - rotatingSprite.parent.x
+ (distance * Math.cos(angle))
- rotatingSprite.halfWidth;
rotatingSprite.y
= centerSprite.centerY - rotatingSprite.parent.y//centerSprite.y
+ (distance * Math.sin(angle))
- rotatingSprite.halfWidth;
};
//### rotateAroundPoint
//Make a point rotate around another point.
//If distanceX and distanceY are the same value, the rotation will
//be circular. If they're different values, the rotation will be
//ellipical.
ga.rotateAroundPoint = function(pointX, pointY, distanceX, distanceY, angle) {
var point = {};
point.x = pointX + Math.cos(angle) * distanceX;
point.y = pointY + Math.sin(angle) * distanceY;
return point;
};
/*
### angle
Return the angle in Radians between two sprites.
Parameters:
a. A sprite object with `centerX` and `centerY` properties.
b. A sprite object with `centerX` and `centerY` properties.
You can use it to make a sprite rotate towards another sprite like this:
box.rotation = angle(box, pointer);
*/
ga.angle = function(s1, s2) {
return Math.atan2(
s2.centerY - s1.centerY,
s2.centerX - s1.centerX
);
};
/*
### random
Returns a random integer between a minimum and maximum value
Parameters:
a. An integer.
b. An integer.
Here's how you can use it to get a random number between, 1 and 10:
randomInt(1, 10);
*/
ga.randomInt = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
//### randomFloat
// Returns a random floating point number between a minimum and maximum value
ga.randomFloat = function(min, max) {
return min + Math.random()*(max-min);
}
//### wait
ga.wait = function(duration, callBack) {
return setTimeout(callBack, duration);
};
//### worldCamera
/*
The `worldCamera` method returns a `camera` object
with `x` and `y` properties. It has
two useful methods: `centerOver`, to center the camera over
a sprite, and `follow` to make it follow a sprite.
`worldCamera` arguments: worldObject, theCanvas
The worldObject needs to have a `width` and `height` property.
*/
ga.worldCamera = function(world, canvas) {
var camera = {
width: canvas.width,
height: canvas.height,
_x: 0,
_y: 0,
//`x` and `y` getters/setters
//When you change the camera's position,
//they acutally reposition the world
get x() {
return this._x;
},
set x(value) {
this._x = value;
world.x = -this._x;
world._previousX = world.x;
},
get y() {
return this._y;
},
set y(value) {
this._y = value;
world.y = -this._y;
world._previousY = world.y;
},
get centerX() {
return this.x + (this.width / 2);
},
get centerY() {
return this.y + (this.height / 2);
},
get rightInnerBoundary() {
return this.x + (this.width / 2) + (this.width / 4);
},
get leftInnerBoundary() {
return this.x + (this.width / 2) - (this.width / 4);
},
get topInnerBoundary() {
return this.y + (this.height / 2) - (this.height / 4);
},
get bottomInnerBoundary() {
return this.y + (this.height / 2) + (this.height / 4);
},
follow: function(sprite) {
//Check the sprites position in relation to the inner boundary
if(sprite.x < this.leftInnerBoundary) {
//Move the camera to follow the sprite if the sprite strays outside
//this.x = Math.floor(sprite.x - (this.width / 4));
this.x = sprite.x - (this.width / 4);
}
if(sprite.y < this.topInnerBoundary) {
//this.y = Math.floor(sprite.y - (this.height / 4));
this.y = sprite.y - (this.height / 4);
}
if(sprite.x + sprite.width > this.rightInnerBoundary) {
//this.x = Math.floor(sprite.x + sprite.width - (this.width / 4 * 3));
this.x = sprite.x + sprite.width - (this.width / 4 * 3);
}
if(sprite.y + sprite.height > this.bottomInnerBoundary) {
//this.y = Math.floor(sprite.y + sprite.height - (this.height / 4 * 3));
this.y = sprite.y + sprite.height - (this.height / 4 * 3);
}
//If the camera reaches the edge of the map, stop it from moving
if(this.x < 0) {
this.x = 0;
}
if(this.y < 0) {
this.y = 0;
}
if(this.x + this.width > world.width) {
this.x = world.width - this.width;
}
if(this.y + this.height > world.height) {
this.y = world.height - this.height;
}
},
centerOver: function(sprite) {
//Center the camera over a sprite
this.x = (sprite.x + sprite.halfWidth) - (this.width / 2);
this.y = (sprite.y + sprite.halfHeight) - (this.height / 2);
}
};
return camera;
};
/*
ga.worldCamera = function(world, canvas) {
var camera = ga.group();
camera.width = canvas.width;
camera.height = canvas.height;
camera._x = 0;
camera._y = 0;
Object.defineProperties(camera, {
x: {
get: function() {
return this._x;
},
set: function(value) {
this._x = value;
world.x = -this._x;
//world._previousX = world.x;
},
enumerable: true, configurable: true
},
y: {
get: function() {
return this._y;
},
set: function(value) {
this._y = value;
world.y = -this._y;
//world._previousY = world.y;
},
enumerable: true, configurable: true
},
rightInnerBoundary: {
get: function() {
return this.x + (this.width / 2) + (this.width / 4);
},
enumerable: true, configurable: true
},
leftInnerBoundary: {
get: function() {
return this.x + (this.width / 2) - (this.width / 4);
},
enumerable: true, configurable: true
},
topInnerBoundary: {
get: function() {
return this.y + (this.height / 2) - (this.height / 4);
},
enumerable: true, configurable: true
},
bottomInnerBoundary: {
get: function() {
return this.y + (this.height / 2) + (this.height / 4);
},
enumerable: true, configurable: true
}
});
camera.follow = function(sprite) {
//Check the sprites position in relation to the inner boundary
if(sprite.x < this.leftInnerBoundary) {
//Move the camera to follow the sprite if the sprite strays outside
this.x = Math.floor(sprite.x - (this.width / 4));
}
if(sprite.y < this.topInnerBoundary) {
this.y = Math.floor(sprite.y - (this.height / 4));
}
if(sprite.x + sprite.width > this.rightInnerBoundary) {
this.x = Math.floor(sprite.x + sprite.width - (this.width / 4 * 3));
}
if(sprite.y + sprite.height > this.bottomInnerBoundary) {
this.y = Math.floor(sprite.y + sprite.height - (this.height / 4 * 3));
}
//If the camera reaches the edge of the map, stop it from moving
if(this.x < 0) {
this.x = 0;
}
if(this.y < 0) {
this.y = 0;
}
if(this.x + this.width > world.width) {
this.x = world.width - this.width;
}
if(this.y + this.height > world.height) {
this.y = world.height - this.height;
}
};
camera.centerOver = function(sprite) {
//Center the camera over a sprite
this.x = (sprite.x + sprite.halfWidth) - (this.width / 2);
this.y = (sprite.y + sprite.halfHeight) - (this.height / 2);
console.log(world)
};
return camera;
};
*/
//### scaleToWindow
//Center and scale the game engine inside the HTML page
ga.scaleToWindow = function(backgroundColor) {
backgroundColor = backgroundColor || "#2C3539";
var scaleX, scaleY, scale, center;
//1. Scale the canvas to the correct size
//Figure out the scale amount on each axis
scaleX = window.innerWidth / ga.canvas.width;
scaleY = window.innerHeight / ga.canvas.height;
//Scale the canvas based on whichever value is less: `scaleX` or `scaleY`
scale = Math.min(scaleX, scaleY);
ga.canvas.style.transformOrigin = "0 0";
ga.canvas.style.transform = "scale(" + scale + ")";
//2. Center the canvas.
//Decide whether to center the canvas vertically or horizontally.
//Wide canvases should be centered vertically, and
//square or tall canvases should be centered horizontally
if (ga.canvas.width > ga.canvas.height) {
if (ga.canvas.width * scale < window.innerWidth) {
center = "horizontally";
} else {
center = "vertically";
}
} else {
if (ga.canvas.height * scale < window.innerHeight) {
center = "vertically";
} else {
center = "horizontally";
}
}
//Center horizontally (for square or tall canvases)
var margin;
if (center === "horizontally") {
margin = (window.innerWidth - ga.canvas.width * scale) / 2;
ga.canvas.style.marginLeft = margin + "px";
ga.canvas.style.marginRight = margin + "px";
}
//Center vertically (for wide canvases)
if (center === "vertically") {
margin = (window.innerHeight - ga.canvas.height * scale) / 2;
ga.canvas.style.marginTop = margin + "px";
ga.canvas.style.marginBottom = margin + "px";
}
//3. Remove any padding from the canvas and body and set the canvas
//display style to "block"
ga.canvas.style.paddingLeft = 0;
ga.canvas.style.paddingRight = 0;
ga.canvas.style.paddingTop = 0;
ga.canvas.style.paddingBottom = 0;
ga.canvas.style.display = "block";
//4. Set the color of the HTML body background
document.body.style.backgroundColor = backgroundColor;
//5. Set the game engine and pointer to the correct scale.
//This is important for correct hit testing between the pointer and sprites
ga.pointer.scale = scale;
ga.scale = scale;
//It's important to set `canvasHasBeenScaled` to `true` so that
//the scale values aren't overridden by Ga's check for fullscreen
//mode in the `update` function (in the `ga.js` file.)
ga.canvas.scaled = true;
//Fix some quirkiness in scaling for Safari
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("safari") != -1) {
if (ua.indexOf("chrome") > -1) {
// Chrome
} else {
// Safari
ga.canvas.style.maxHeight = "100%";
ga.canvas.style.minHeight = "100%";
}
}
};
//### scaleToFit - DEPRICATED - DO NOT USE!
/*
Center and scale Ga inside the HTML page. The `dimension` can be either "width" or "height"
depending on you want to center the game horizontally ("width") or vertically ("height").
*/
ga.scaleToFit = function(dimension, color) {
var scaleX, scaleY, scale;
if (dimension === "width") {
scaleX = ga.canvas.width / window.innerWidth;
scaleY = ga.canvas.height / window.innerHeight;
}
if (dimension === "height") {
scaleX = window.innerWidth / ga.canvas.width;
scaleY = window.innerHeight / ga.canvas.height;
}
scale = Math.min(scaleX, scaleY);
ga.canvas.style.transformOrigin = "0 0";
ga.canvas.style.transform = "scale(" + scale + ")";
//Set the color of the HTML body background
document.body.style.backgroundColor = color;
//Center the canvas in the HTML body
ga.canvas.style.paddingLeft = 0;
ga.canvas.style.paddingRight = 0;
ga.canvas.style.marginLeft = "auto";
ga.canvas.style.marginRight = "auto";
ga.canvas.style.display = "block";
ga.canvas.style.minHeight = "100%";
//Fix some quirkiness in scaling for Safari
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
// Chrome
} else {
// Safari
ga.canvas.style.maxHeight = "100%";
ga.canvas.style.minHeight = "100%";
}
}
//Set ga to the correct scale. This important for correct hit testing
//between the pointer and sprites
ga.scale = scale;
};
/*
###shakingSprites
An array to store all the shaking sprites in the game
*/
ga.shakingSprites = [];
/*
###updateShakingSprites
`updateShakingSprites` loops through all the sprites in `ga.particles`
and runs their `updateParticles` functions.
*/
ga.updateShakingSprites = function() {
//Update all the shaking sprites
if (ga.shakingSprites.length > 0) {
for(var i = ga.shakingSprites.length - 1; i >= 0; i--) {
var shakingSprite = ga.shakingSprites[i];
if (shakingSprite.updateShake) shakingSprite.updateShake();
}
}
}
//Push `updateShakingSprites` into the `ga.updateFunctions` array so that
//it runs inside Ga's game loop. (See the `ga.update` method in the
//`ga.js` file to see how this works.
ga.updateFunctions.push(ga.updateShakingSprites);
/*
shake
-----
Used to create a shaking effect, like a screen shake.
`shake` arguments: sprite, magnitude, angularShake?
Use it like this:
g.shake(sprite, 0.05, true);
If `angularShake?` (the 3rd argument) is `true`, the sprite will shake around
its axis. The `magnitude` will be the maximum value, in
radians, that it should shake.
If `angularShake?` is `false` the shake effect will happen on the x/y axis.
g.shake(sprite, 16, false);
In that case the magnitude will be the maximum amount of
displacement, in pixels.
*/
ga.shake = function(sprite, magnitude, angular) {
if (magnitude === undefined) magnitude = 16;
if (angular === undefined) angular = false;
//A counter to count the number of shakes
var counter = 1;
//The total number of shakes (there will be 1 shake per frame)
var numberOfShakes = 10;
//Capture the sprite's position and angle so you can
//restore them after the shaking has finished
var startX = sprite.x,
startY = sprite.y,
startAngle = sprite.rotation;
//Divide the magnitude into 10 units so that you can
//reduce the amount of shake by 10 percent each frame
var magnitudeUnit = magnitude / numberOfShakes;
//The `randomInt` helper function
var randomInt = function(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
};
//Add the sprite to the `shakingSprites` array if it
//isn't already there
if(ga.shakingSprites.indexOf(sprite) === -1) {
ga.shakingSprites.push(sprite);
//Add an `updateShake` method to the sprite.
//The `updateShake` method will be called each frame
//in the game loop. The shake effect type can be either
//up and down (x/y shaking) or angular (rotational shaking).
sprite.updateShake = function(){
if(angular) {
angularShake();
} else {
upAndDownShake();
}
};
}
//The `upAndDownShake` function
function upAndDownShake() {
//Shake the sprite while the `counter` is less than
//the `numberOfShakes`
if (counter < numberOfShakes) {
//Reset the sprite's position at the start of each shake