forked from onaluf/gameQuery
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.gamequery.js
1443 lines (1315 loc) · 67 KB
/
jquery.gamequery.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
/*
* gameQuery rev. $Revision$
*
* Copyright (c) 2008 Selim Arsever (gamequery.onaluf.org)
* licensed under the MIT (MIT-LICENSE.txt)
*/
// this allows use of the convenient $ notation in a plugin
(function($) {
/**
* Constants
*/
/**
* This namespace will be prepended to data values stored by this plugin.
*/
var GAMEQUERY_NAMESPACE = 'GAMEQUERY__';
$.extend({ gameQuery: {
/**
* This is the Animation Object
*/
Animation: function (options) {
// private default values
var defaults = {
imageURL: "",
numberOfFrame: 1,
delta: 0,
rate: 30,
type: 0,
distance: 0,
offsetx: 0,
offsety: 0
};
// options extends defaults
options = $.extend(defaults, options);
//"public" attributes:
this.imageURL = options.imageURL; // The url of the image to be used as an animation or sprite
this.numberOfFrame = options.numberOfFrame;// The number of frames to be displayed when playing the animation
this.delta = options.delta; // The distance in pixels between two frames
this.rate = options.rate; // The rate at which the frames change in miliseconds
this.type = options.type; // The type of the animation.This is a bitwise OR of the properties.
this.distance = options.distance; // The distance in pixels between two animations
this.offsetx = options.offsetx; // The x coordinate where the first sprite begins
this.offsety = options.offsety; // The y coordinate where the first sprite begins
//Whenever a new animation is created we add it to the ResourceManager animation list
$.gameQuery.resourceManager.addAnimation(this);
return true;
},
// "constants" for the different types of an animation
ANIMATION_VERTICAL: 1, // Generated by a vertical offset of the background
ANIMATION_HORIZONTAL: 2, // Generated by a horizontal offset of the background
ANIMATION_ONCE: 4, // Played only once (else looping indefinitely)
ANIMATION_CALLBACK: 8, // A callback is exectued at the end of a cycle
ANIMATION_MULTI: 16, // The image file contains many animations
ANIMATION_PINGPONG: 32, // At the last frame of the animation it reverses
// (if used in conjunction with ONCE it will have no effect)
// "constants" for the different type of geometry for a sprite
GEOMETRY_RECTANGLE: 1,
GEOMETRY_DISC: 2,
// basic values
refreshRate: 30,
/**
* An object to manage resource loading
*/
resourceManager: {
animations: [], // List of animations / images used in the game
sounds: [], // List of sounds used in the game
callbacks: [], // List of the functions called at each refresh
running: false, // State of the game,
/**
* Loads resources before starting the game.
*/
preload: function() {
//Start loading the images
for (var i = this.animations.length-1 ; i >= 0; i --){
this.animations[i].domO = new Image();
this.animations[i].domO.src = this.animations[i].imageURL;
}
//Start loading the sounds
for (var i = this.sounds.length-1 ; i >= 0; i --){
this.sounds[i].load();
}
$.gameQuery.resourceManager.waitForResources();
},
/**
* Waits for all the resources called for in preload() to finish loading.
*/
waitForResources: function() {
var loadbarEnabled = ($.gameQuery.loadbar != undefined);
if(loadbarEnabled){
$($.gameQuery.loadbar.id).width(0);
var loadBarIncremant = $.gameQuery.loadbar.width / (this.animations.length + this.sounds.length);
}
//check the images
var imageCount = 0;
for(var i=0; i < this.animations.length; i++){
if(this.animations[i].domO.complete){
imageCount++;
}
}
//check the sounds
var soundCount = 0;
for(var i=0; i < this.sounds.length; i++){
var temp = this.sounds[i].ready();
if(temp){
soundCount++;
}
}
//Call the load callback with the current progress
if($.gameQuery.resourceManager.loadCallback){
var percent = (imageCount+soundCount)/(this.animations.length + this.sounds.length)*100;
$.gameQuery.resourceManager.loadCallback(percent);
}
if(imageCount + soundCount < (this.animations.length + this.sounds.length)){
imgWait=setTimeout(function () {
$.gameQuery.resourceManager.waitForResources();
}, 100);
} else {
// all the resources are loaded!
// We can associate the animation's images to their corresponding sprites
$.gameQuery.scenegraph.children().each(function(){
// recursive call on the children:
$(this).children().each(arguments.callee);
// add the image as a background
if(this.gameQuery && this.gameQuery.animation){
$(this).css("background-image", "url("+this.gameQuery.animation.imageURL+")");
// we set the correct kind of repeat
if(this.gameQuery.animation.type & $.gameQuery.ANIMATION_VERTICAL) {
$(this).css("background-repeat", "repeat-x");
} else if(this.gameQuery.animation.type & $.gameQuery.ANIMATION_HORIZONTAL) {
$(this).css("background-repeat", "repeat-y");
} else {
$(this).css("background-repeat", "no-repeat");
}
}
});
//Launch the refresh loop
$.gameQuery.resourceManager.running = true;
setInterval(function () {
$.gameQuery.resourceManager.refresh();
},($.gameQuery.refreshRate));
if($.gameQuery.startCallback){
$.gameQuery.startCallback();
}
//make the scenegraph visible
$.gameQuery.scenegraph.css("visibility","visible");
}
},
/**
* This function refresh a unique sprite here 'this' represent a dom object
*/
refreshSprite: function() {
//Call this function on all the children:
// is 'this' a sprite ?
if(this.gameQuery != undefined){
var gameQuery = this.gameQuery;
// does 'this' has an animation ?
if(gameQuery.animation){
//Do we have anything to do?
if ( (gameQuery.idleCounter == gameQuery.animation.rate-1) && gameQuery.playing){
// does 'this' loops?
if(gameQuery.animation.type & $.gameQuery.ANIMATION_ONCE){
if(gameQuery.currentFrame < gameQuery.animation.numberOfFrame-2){
gameQuery.currentFrame += gameQuery.frameIncrement;
} else if(gameQuery.currentFrame == gameQuery.animation.numberOfFrame-2) {
gameQuery.currentFrame += gameQuery.frameIncrement;
// does 'this' has a callback ?
if(gameQuery.animation.type & $.gameQuery.ANIMATION_CALLBACK){
if($.isFunction(gameQuery.callback)){
gameQuery.callback(this);
}
}
}
} else {
if(gameQuery.animation.type & $.gameQuery.ANIMATION_PINGPONG){
if(gameQuery.currentFrame == gameQuery.animation.numberOfFrame-1 && gameQuery.frameIncrement == 1) {
gameQuery.frameIncrement = -1;
} else if (gameQuery.currentFrame == 0 && gameQuery.frameIncrement == -1) {
gameQuery.frameIncrement = 1;
}
}
gameQuery.currentFrame = (gameQuery.currentFrame+gameQuery.frameIncrement)%gameQuery.animation.numberOfFrame;
if(gameQuery.currentFrame == 0){
// does 'this' has a callback ?
if(gameQuery.animation.type & $.gameQuery.ANIMATION_CALLBACK){
if($.isFunction(gameQuery.callback)){
gameQuery.callback(this);
}
}
}
}
// update the background:
if(gameQuery.animation.type & $.gameQuery.ANIMATION_VERTICAL){
if(gameQuery.multi){
$(this).css("background-position",""+(-gameQuery.animation.offsetx-gameQuery.multi)+"px "+(-gameQuery.animation.offsety-gameQuery.animation.delta*gameQuery.currentFrame)+"px");
} else {
$(this).css("background-position",""+(-gameQuery.animation.offsetx)+"px "+(-gameQuery.animation.offsety-gameQuery.animation.delta*gameQuery.currentFrame)+"px");
}
} else if(gameQuery.animation.type & $.gameQuery.ANIMATION_HORIZONTAL) {
if(gameQuery.multi){
$(this).css("background-position",""+(-gameQuery.animation.offsetx-gameQuery.animation.delta*gameQuery.currentFrame)+"px "+(-gameQuery.animation.offsety-gameQuery.multi)+"px");
} else {
$(this).css("background-position",""+(-gameQuery.animation.offsetx-gameQuery.animation.delta*gameQuery.currentFrame)+"px "+(-gameQuery.animation.offsety)+"px");
}
}
}
gameQuery.idleCounter = (gameQuery.idleCounter+1)%gameQuery.animation.rate;
}
}
return true;
},
/**
* This function refresh a unique tile-map, here 'this' represent a dom object
*/
refreshTilemap: function() {
//Call this function on all the children:
// is 'this' a sprite ?
if(this.gameQuery != undefined){
var gameQuery = this.gameQuery;
if($.isArray(gameQuery.frameTracker)){
for(var i=0; i<gameQuery.frameTracker.length; i++){
//Do we have anything to do?
if(gameQuery.idleCounter[i] == gameQuery.animations[i].rate-1){
// does 'this' loops?
if(gameQuery.animations[i].type & $.gameQuery.ANIMATION_ONCE){
if(gameQuery.frameTracker[i] < gameQuery.animations[i].numberOfFrame-1){
gameQuery.frameTracker[i] += gameQuery.frameIncrement[i];
}
} else {
if(gameQuery.animations[i].type & $.gameQuery.ANIMATION_PINGPONG){
if(gameQuery.frameTracker[i] == gameQuery.animations[i].numberOfFrame-1 && gameQuery.frameIncrement[i] == 1) {
gameQuery.frameIncrement[i] = -1;
} else if (gameQuery.frameTracker[i] == 0 && gameQuery.frameIncrement[i] == -1) {
gameQuery.frameIncrement[i] = 1;
}
}
gameQuery.frameTracker[i] = (gameQuery.frameTracker[i]+gameQuery.frameIncrement[i])%gameQuery.animations[i].numberOfFrame;
}
}
gameQuery.idleCounter[i] = (gameQuery.idleCounter[i]+1)%gameQuery.animations[i].rate;
}
} else {
//Do we have anything to do?
if(gameQuery.idleCounter == gameQuery.animations.rate-1){
// does 'this' loops?
if(gameQuery.animations.type & $.gameQuery.ANIMATION_ONCE){
if(gameQuery.frameTracker < gameQuery.animations.numberOfFrame-1){
gameQuery.frameTracker += gameQuery.frameIncrement;
}
} else {
if(gameQuery.animations.type & $.gameQuery.ANIMATION_PINGPONG){
if(gameQuery.frameTracker == gameQuery.animations.numberOfFrame-1 && gameQuery.frameIncrement == 1) {
gameQuery.frameIncrement = -1;
} else if (gameQuery.frameTracker == 0 && gameQuery.frameIncrement == -1) {
gameQuery.frameIncrement = 1;
}
}
gameQuery.frameTracker = (gameQuery.frameTracker+gameQuery.frameIncrement)%gameQuery.animations.numberOfFrame;
}
}
gameQuery.idleCounter = (gameQuery.idleCounter+1)%gameQuery.animations.rate;
}
// update the background of all active tiles:
$(this).find(".active").each(function(){
if($.isArray(gameQuery.frameTracker)){
var animationNumber = this.gameQuery.animationNumber
if(gameQuery.animations[animationNumber].type & $.gameQuery.ANIMATION_VERTICAL){
$(this).css("background-position",""+(-gameQuery.animations[animationNumber].offsetx)+"px "+(-gameQuery.animations[animationNumber].offsety-gameQuery.animations[animationNumber].delta*gameQuery.frameTracker[animationNumber])+"px");
} else if(gameQuery.animations[animationNumber].type & $.gameQuery.ANIMATION_HORIZONTAL) {
$(this).css("background-position",""+(-gameQuery.animations[animationNumber].offsetx-gameQuery.animations[animationNumber].delta*gameQuery.frameTracker[animationNumber])+"px "+(-gameQuery.animations[animationNumber].offsety)+"px");
}
} else {
if(gameQuery.animations.type & $.gameQuery.ANIMATION_VERTICAL){
$(this).css("background-position",""+(-gameQuery.animations.offsetx-this.gameQuery.multi)+"px "+(-gameQuery.animations.offsety-gameQuery.animations.delta*gameQuery.frameTracker)+"px");
} else if(gameQuery.animations.type & $.gameQuery.ANIMATION_HORIZONTAL) {
$(this).css("background-position",""+(-gameQuery.animations.offsetx-gameQuery.animations.delta*gameQuery.frameTracker)+"px "+(-gameQuery.animations.offsety-this.gameQuery.multi)+"px");
}
}
});
}
return true;
},
/**
* Called periodically to refresh the state of the game.
*/
refresh: function() {
$.gameQuery.playground.find(".sprite").each(this.refreshSprite);
$.gameQuery.playground.find(".tileSet").each(this.refreshTilemap);
var deadCallback= new Array();
for (var i = this.callbacks.length-1; i >= 0; i--){
if(this.callbacks[i].idleCounter == this.callbacks[i].rate-1){
var returnedValue = this.callbacks[i].fn();
if(typeof returnedValue == 'boolean'){
// if we have a boolean: 'true' means 'no more execution', 'false' means 'execute once more'
if(returnedValue){
deadCallback.push(i);
}
} else if(typeof returnedValue == 'number') {
// if we have a number it re-defines the time to the next call
this.callbacks[i].rate = Math.round(returnedValue/$.gameQuery.refreshRate);
this.callbacks[i].idleCounter = 0;
}
}
this.callbacks[i].idleCounter = (this.callbacks[i].idleCounter+1)%this.callbacks[i].rate;
}
for(var i = deadCallback.length-1; i >= 0; i--){
this.callbacks.splice(deadCallback[i],1);
}
},
addAnimation: function(animation) {
if($.inArray(animation,this.animations)<0){
//normalize the animation rate:
animation.rate = Math.round(animation.rate/$.gameQuery.refreshRate);
if(animation.rate==0){
animation.rate = 1;
}
this.animations.push(animation);
}
},
addSound: function(sound){
if($.inArray(sound,this.sounds)<0){
this.sounds.push(sound);
}
},
registerCallback: function(fn, rate){
rate = Math.round(rate/$.gameQuery.refreshRate);
if(rate==0){
rate = 1;
}
this.callbacks.push({fn: fn, rate: rate, idleCounter: 0});
}
},
// This is a single place to update the underlying data of sprites/groups/tiles
update: function(descriptor, transformation) {
// Did we really receive a descriptor or a jQuery object instead?
if(!$.isPlainObject(descriptor)){
// Then we must get real descriptor
if(descriptor.length > 0){
var gameQuery = descriptor[0].gameQuery;
} else {
var gameQuery = descriptor.gameQuery;
}
} else {
var gameQuery = descriptor;
}
// If we couldn't find one we return
if(!gameQuery) return;
if(gameQuery.tileSet === true){
//then we have a tilemap!
descriptor = $(descriptor);
// find the tilemap offset relative to the playground:
var playgroundOffset = $.gameQuery.playground.offset();
var tileSetOffset = descriptor.offset();
tileSetOffset = {top: tileSetOffset.top - playgroundOffset.top, left: tileSetOffset.left - playgroundOffset.left};
// test what kind of transformation we have and react accordingly:
// Update the descriptor
for(property in transformation){
switch(property){
case "x":
//Do we need to activate/deactivate the first/last column
var left = parseFloat(transformation.left);
//Get the tileSet offset (relative to the playground)
var playgroundOffset = $.gameQuery.playground.offset();
var tileSetOffset = descriptor.parent().offset();
tileSetOffset = {top: tileSetOffset.top - playgroundOffset.top, left: tileSetOffset.left + left - playgroundOffset.left};
//activates the visible tiles
var firstColumn = Math.max(Math.min(Math.floor(-tileSetOffset.left/gameQuery.width), gameQuery.sizex),0);
var lastColumn = Math.max(Math.min(Math.ceil(($.gameQuery.playground[0].width-tileSetOffset.left)/gameQuery.width), gameQuery.sizex),0);
for(var i = gameQuery.firstRow; i < gameQuery.lastRow; i++){
// if old first col < new first col
// deactivate the newly invisible tiles
for(var j = gameQuery.firstColumn; j < firstColumn ; j++) {
$("#tile_"+descriptor.attr("id")+"_"+i+"_"+j).removeClass("active");
}
//and activate the newly visible tiles
for(var j = gameQuery.lastColumn; j < lastColumn ; j++) {
$("#tile_"+descriptor.attr("id")+"_"+i+"_"+j).addClass("active");
}
// if old first col > new first col
// deactivate the newly invisible tiles
for(var j = lastColumn; j < gameQuery.lastColumn ; j++) {
$("#tile_"+descriptor.attr("id")+"_"+i+"_"+j).removeClass("active");
}
//activate the newly visible tiles
for(var j = firstColumn; j < gameQuery.firstColumn ; j++) {
$("#tile_"+descriptor.attr("id")+"_"+i+"_"+j).addClass("active");
}
}
gameQuery.firstColumn = firstColumn;
gameQuery.lastColumn = lastColumn;
break;
case "y":
//Do we need to activate/deactivate the first/last row
var top = parseFloat(transformation.top);
//Get the tileSet offset (relative to the playground)
var playgroundOffset = $.gameQuery.playground.offset();
var tileSetOffset = descriptor.parent().offset();
tileSetOffset = {top: tileSetOffset.top + top - playgroundOffset.top, left: tileSetOffset.left - playgroundOffset.left};
//actvates the visible tiles
var firstRow = Math.max(Math.min(Math.floor(-tileSetOffset.top/gameQuery.height), gameQuery.sizey), 0);
var lastRow = Math.max(Math.min(Math.ceil(($.gameQuery.playground[0].height-tileSetOffset.top)/gameQuery.height), gameQuery.sizey), 0);
for(var j = gameQuery.firstColumn; j < gameQuery.lastColumn ; j++) {
// if old first row < new first row
// deactivate the newly invisible tiles
for(var i = gameQuery.firstRow; i < firstRow; i++){
$("#tile_"+descriptor.attr("id")+"_"+i+"_"+j).removeClass("active");
}
//and activate the newly visible tiles
for(var i = gameQuery.lastRow; i < lastRow; i++){
$("#tile_"+descriptor.attr("id")+"_"+i+"_"+j).addClass("active");
}
// if old first row < new first row
// deactivate the newly invisible tiles
for(var i = lastRow; i < gameQuery.lastRow; i++){
$("#tile_"+descriptor.attr("id")+"_"+i+"_"+j).removeClass("active");
}
//and activate the newly visible tiles
for(var i = firstRow; i < gameQuery.firstRow; i++){
$("#tile_"+descriptor.attr("id")+"_"+i+"_"+j).addClass("active");
}
}
gameQuery.firstRow = firstRow;
gameQuery.lastRow = lastRow;
break;
case "angle": //(in degree)
//TODO
break;
case "factor":
//TODO
break;
}
}
} else {
var refreshBoundingCircle = $.gameQuery.playground && !$.gameQuery.playground.disableCollision;
// Update the descriptor
for(property in transformation){
switch(property){
case "x":
if(refreshBoundingCircle){
gameQuery.boundingCircle.x = gameQuery.posx+gameQuery.width/2;
}
break;
case "y":
if(refreshBoundingCircle){
gameQuery.boundingCircle.y = gameQuery.posy+gameQuery.height/2;
}
break;
case "w":
case "h":
gameQuery.boundingCircle.originalRadius = Math.sqrt(Math.pow(gameQuery.width,2) + Math.pow(gameQuery.height,2))/2
gameQuery.boundingCircle.radius = gameQuery.factor*gameQuery.boundingCircle.originalRadius;
break;
case "angle": //(in degrees)
gameQuery.angle = parseFloat(transformation.angle);
break;
case "factor":
gameQuery.factor = parseFloat(transformation.factor);
if(refreshBoundingCircle){
gameQuery.boundingCircle.radius = gameQuery.factor*gameQuery.boundingCircle.originalRadius;
}
break;
}
}
}
},
/**
* Utility function that returns the radius for a geometry
*
* @param {object} elem DOM element
* @param {float} angle the angle in degrees
* @return {object} .x, .y radius of geometry
*/
proj: function (elem, angle) {
switch (elem.geometry){
case $.gameQuery.GEOMETRY_RECTANGLE :
var b = angle*Math.PI*2/360;
var Rx = Math.abs(Math.cos(b)*elem.width/2*elem.factor)+Math.abs(Math.sin(b)*elem.height/2*elem.factor);
var Ry = Math.abs(Math.cos(b)*elem.height/2*elem.factor)+Math.abs(Math.sin(b)*elem.width/2*elem.factor);
return {x: Rx, y: Ry};
}
},
//Utility function for collision of two objects
collide: function(elem1, offset1, elem2, offset2) {
// test real collision (only for two rectangles...)
if((elem1.geometry == $.gameQuery.GEOMETRY_RECTANGLE && elem2.geometry == $.gameQuery.GEOMETRY_RECTANGLE)){
var dx = offset2.x + elem2.boundingCircle.x - elem1.boundingCircle.x - offset1.x;
var dy = offset2.y + elem2.boundingCircle.y - elem1.boundingCircle.y - offset1.y;
var a = Math.atan(dy/dx);
var Dx = Math.abs(Math.cos(a-elem1.angle*Math.PI*2/360)/Math.cos(a)*dx);
var Dy = Math.abs(Math.sin(a-elem1.angle*Math.PI*2/360)/Math.sin(a)*dy);
var R = $.gameQuery.proj(elem2, elem2.angle-elem1.angle);
if((elem1.width/2*elem1.factor+R.x <= Dx) || (elem1.height/2*elem1.factor+R.y <= Dy)) {
return false;
} else {
var Dx = Math.abs(Math.cos(a-elem2.angle*Math.PI*2/360)/Math.cos(a)*-dx);
var Dy = Math.abs(Math.sin(a-elem2.angle*Math.PI*2/360)/Math.sin(a)*-dy);
var R = $.gameQuery.proj(elem1, elem1.angle-elem2.angle);
if((elem2.width/2*elem2.factor+R.x <= Dx) || (elem2.height/2*elem2.factor+R.y <= Dy)) {
return false;
} else {
return true;
}
}
} else {
return false;
}
}
},
//Mute (or unmute) all the sounds.
muteSound: function(muted){
for (var i = $.gameQuery.resourceManager.sounds-1 ; i >= 0; i --) {
$.gameQuery.resourceManager.sounds[i].muted(muted);
}
},
playground: function() {
return $.gameQuery.playground
},
/**
* Define a callback called during the loading of the game's resources.
*
* The function will recieve as unique parameter
* a number representing the progess percentage.
*/
loadCallback: function(callback){
$.gameQuery.resourceManager.loadCallback = callback;
}});
$.fn.extend({
/**
* Define the div which contains the game and initialize it.
* This could be called on any node it doesn't matter.
* The returned node is the playground node.
* This IS a destructive call
*/
playground: function(options) {
if(this.length == 1){
if(this[0] == document){ // Old usage check
throw "Old playground usage, use $.playground() to retreive the playground and $('mydiv').playground(options) to set the div!";
}
options = $.extend({
height: 320,
width: 480,
refreshRate: 30,
position: "absolute",
keyTracker: false,
disableCollision: false
}, options);
//We save the playground node and set some variable for this node:
$.gameQuery.playground = this;
$.gameQuery.refreshRate = options.refreshRate;
$.gameQuery.playground[0].height = options.height;
$.gameQuery.playground[0].width = options.width;
// We initialize the display of the div
$.gameQuery.playground.css({
position: options.position,
display: "block",
overflow: "hidden",
height: options.height+"px",
width: options.width+"px"
})
.append("<div id='scenegraph' style='visibility: hidden'/>");
$.gameQuery.scenegraph = $("#scenegraph");
//Add the keyTracker to the gameQuery object:
$.gameQuery.keyTracker = {};
// we only enable the real tracking if the users wants it
if(options.keyTracker){
$(document).keydown(function(event){
$.gameQuery.keyTracker[event.keyCode] = true;
});
$(document).keyup(function(event){
$.gameQuery.keyTracker[event.keyCode] = false;
});
}
}
return this;
},
/**
* Starts the game.
*
* Resources from the resource manager are preloaded if necesary
* Works only for the playground node.
* This is a non-destructive call
*/
startGame: function(callback) {
//if the element is the playground we start the game:
$.gameQuery.startCallback = callback;
$.gameQuery.resourceManager.preload();
return this;
},
/**
* Add a group to the scene graph
*
* Works only on the scenegraph root or on another group
* This IS a destructive call and should be terminated with end()
* to go back one level up in the chaining
*/
addGroup: function(group, options) {
options = $.extend({
width: 32,
height: 32,
posx: 0,
posy: 0,
posz: 0,
posOffsetX: 0,
posOffsetY: 0,
overflow: "visible",
geometry: $.gameQuery.GEOMETRY_RECTANGLE,
angle: 0,
factor: 1,
factorh: 1,
factorv: 1
}, options);
var newGroupElement = "<div id='"+group+"' class='group' style='position: absolute; display: block; overflow: "+options.overflow+"; top: "+options.posy+"px; left: "+options.posx+"px; height: "+options.height+"px; width: "+options.width+"px;' />";
if(this == $.gameQuery.playground){
$.gameQuery.scenegraph.append(newGroupElement);
} else if ((this == $.gameQuery.scenegraph)||(this.hasClass("group"))){
this.append(newGroupElement);
}
var newGroup = $("#"+group);
newGroup[0].gameQuery = options;
newGroup[0].gameQuery.boundingCircle = {x: options.posx + options.width/2,
y: options.posy + options.height/0,
originalRadius: Math.sqrt(Math.pow(options.width,2) + Math.pow(options.height,2))/2};
newGroup[0].gameQuery.boundingCircle.radius = newGroup[0].gameQuery.boundingCircle.originalRadius;
newGroup[0].gameQuery.group = true;
return this.pushStack(newGroup);
},
/**
* Add a sprite to the current node.
* Works only on the playground, the scenegraph root or a scenegraph group
* This is a non-destructive call
*/
addSprite: function(sprite, options) {
options = $.extend({
width: 32,
height: 32,
posx: 0,
posy: 0,
posz: 0,
posOffsetX: 0,
posOffsetY: 0,
idleCounter: 0,
currentFrame: 0,
frameIncrement: 1,
geometry: $.gameQuery.GEOMETRY_RECTANGLE,
angle: 0,
factor: 1,
playing: true,
factorh: 1,
factorv: 1
}, options);
var newSpriteElem = "<div id='"+sprite+"' class='sprite' style='position: absolute; display: block; overflow: hidden; height: "+options.height+"px; width: "+options.width+"px; left: "+options.posx+"px; top: "+options.posy+"px; background-position: "+((options.animation)? -options.animation.offsetx : 0)+"px "+((options.animation)? -options.animation.offsety : 0)+"px;' />";
if(this == $.gameQuery.playground){
$.gameQuery.scenegraph.append(newSpriteElem);
} else {
this.append(newSpriteElem);
}
//if the game has already started we want to add the animation's image as a background now:
if(options.animation){
// the second test is a fix for default background (https://github.com/onaluf/gameQuery/issues/3)
if($.gameQuery.resourceManager.running && options.animation.imageURL !== ''){
$("#"+sprite).css("background-image", "url("+options.animation.imageURL+")");
}
if(options.animation.type & $.gameQuery.ANIMATION_VERTICAL) {
$("#"+sprite).css("background-repeat", "repeat-x");
} else if(options.animation.type & $.gameQuery.ANIMATION_HORIZONTAL) {
$("#"+sprite).css("background-repeat", "repeat-y");
} else {
$("#"+sprite).css("background-repeat", "no-repeat");
}
}
var spriteDOMObject = $("#"+sprite)[0];
if(spriteDOMObject != undefined){
spriteDOMObject.gameQuery = options;
//Compute bounding Circle:
spriteDOMObject.gameQuery.boundingCircle = {x: options.posx + options.width/2,
y: options.posy + options.height/2,
originalRadius: Math.sqrt(Math.pow(options.width,2) + Math.pow(options.height,2))/2};
spriteDOMObject.gameQuery.boundingCircle.radius = spriteDOMObject.gameQuery.boundingCircle.originalRadius;
}
return this;
},
/**
* Remove the sprite on which it is called.
*
* This is here for backward compatibility but it doesn't do anything
* more than simply call .remove()
* This is a non-destructive call.
*/
removeSprite: function() {
this.remove();
return this;
},
/**
* Add a Tile Map to the selected element.
* This is a non-destructive call.
*/
addTilemap: function(name, tileDescription, animationList, options){
options = $.extend({
width: 32,
height: 32,
sizex: 32,
sizey: 32,
posx: 0,
posy: 0,
posz: 0,
posOffsetX: 0,
posOffsetY: 0,
factorh: 1,
factorv: 1
}, options);
var tileSet = $("<div class='tileSet' style='position: absolute; display: block; overflow: hidden;' />");
tileSet.css({top: options.posy, left: options.posx, height: options.height*options.sizey, width: options.width*options.sizex}).attr("id",name);
if(this == $.gameQuery.playground){
$.gameQuery.scenegraph.append(tileSet);
} else {
this.append(tileSet);
}
if($.isArray(animationList)){
var frameTracker = [];
var idleCounter = [];
var frameIncrement = [];
for(var i=0; i<animationList.length; i++){
frameTracker[i] = 0;
idleCounter[i] = 0;
frameIncrement[i] = 1;
}
tileSet[0].gameQuery = options
tileSet[0].gameQuery.frameTracker = frameTracker;
tileSet[0].gameQuery.animations = animationList;
tileSet[0].gameQuery.idleCounter = idleCounter;
tileSet[0].gameQuery.frameIncrement = frameIncrement;
tileSet[0].gameQuery.tileSet = true;
} else {
tileSet[0].gameQuery = options
tileSet[0].gameQuery.frameTracker = 0;
tileSet[0].gameQuery.frameIncrement = 1;
tileSet[0].gameQuery.animations = animationList;
tileSet[0].gameQuery.idleCounter = 0;
tileSet[0].gameQuery.tileSet = true;
}
if(typeof tileDescription == "function"){
for(var i=0; i<options.sizey; i++){
for(var j=0; j<options.sizex; j++){
if(tileDescription(i,j) != 0){
if($.isArray(animationList)){
// for many simple animation:
tileSet.addSprite("tile_"+name+"_"+i+"_"+j,
{width: options.width,
height: options.height,
posx: j*options.width,
posy: i*options.height,
animation: animationList[tileDescription(i,j)-1]});
var newTile = $("#tile_"+name+"_"+i+"_"+j);
newTile.removeClass("sprite");
newTile.addClass("tileType_"+(tileDescription(i,j)-1));
newTile[0].gameQuery.animationNumber = tileDescription(i,j)-1;
} else {
// for multi-animation:
tileSet.addSprite("tile_"+name+"_"+i+"_"+j,
{width: options.width,
height: options.height,
posx: j*options.width,
posy: i*options.height,
animation: animationList});
var newTile = $("#tile_"+name+"_"+i+"_"+j);
newTile.setAnimation(tileDescription(i,j)-1);
newTile.removeClass("sprite");
newTile.addClass("tileType_"+(tileDescription(i,j)-1));
}
}
}
}
} else if(typeof tileDescription == "object") {
for(var i=0; i<tileDescription.length; i++){
for(var j=0; j<tileDescription[0].length; j++){
if(tileDescription[i][j] != 0){
if($.isArray(animationList)){
// for many simple animation:
tileSet.addSprite("tile_"+name+"_"+i+"_"+j,
{width: options.width,
height: options.height,
posx: j*options.width,
posy: i*options.height,
animation: animationList[tileDescription[i][j]-1]});
var newTile = $("#tile_"+name+"_"+i+"_"+j);
newTile.removeClass("sprite");
newTile.addClass("tileType_"+(tileDescription[i][j]-1));
newTile[0].gameQuery.animationNumber = tileDescription[i][j]-1;
} else {
// for multi-animation:
tileSet.addSprite("tile_"+name+"_"+i+"_"+j,
{width: options.width,
height: options.height,
posx: j*options.width,
posy: i*options.height,
animation: animationList});
var newTile = $("#tile_"+name+"_"+i+"_"+j);
newTile.setAnimation(tileDescription[i][j]-1);
newTile.removeClass("active");
newTile.addClass("tileType_"+(tileDescription[i][j]-1));
}
}
}
}
}
//Get the tileSet offset (relative to the playground)
var playgroundOffset = $.gameQuery.playground.offset();
var tileSetOffset = tileSet.offset();
tileSetOffset = {top: tileSetOffset.top - playgroundOffset.top, left: tileSetOffset.left - playgroundOffset.left};
//activates the visible tiles
var firstRow = Math.max(Math.min(Math.floor(-tileSetOffset.top/options.height), options.sizey), 0);
var lastRow = Math.max(Math.min(Math.ceil(($.gameQuery.playground[0].height-tileSetOffset.top)/options.height), options.sizey), 0);
var firstColumn = Math.max(Math.min(Math.floor(-tileSetOffset.left/options.width), options.sizex), 0);
var lastColumn = Math.max(Math.min(Math.ceil(($.gameQuery.playground[0].width-tileSetOffset.left)/options.width), options.sizex), 0);
tileSet[0].gameQuery.firstRow = firstRow;
tileSet[0].gameQuery.lastRow = lastRow;
tileSet[0].gameQuery.firstColumn = firstColumn;
tileSet[0].gameQuery.lastColumn = lastColumn;
for(var i = firstRow; i < lastRow; i++){
for(var j = firstColumn; j < lastColumn ; j++) {
$("#tile_"+name+"_"+i+"_"+j).toggleClass("active");
}
}
return this.pushStack(tileSet);
},
/**
* Stop the animation at the current frame
*/
pauseAnimation: function() {
this[0].gameQuery.playing = false;
return this;
},
/**
* Resume the animation (if paused)
*/
resumeAnimation: function() {
this[0].gameQuery.playing = true;
return this;
},
/**
* Changes the animation associated with a sprite.
*
* WARNING: no checks are made to ensure that the object is really a sprite
* This is a non-destructive call
*/
setAnimation: function(animation, callback) {
var gameQuery = this[0].gameQuery;
if(typeof animation == "number"){
if(gameQuery.animation.type & $.gameQuery.ANIMATION_MULTI){
var distance = gameQuery.animation.distance * animation;
gameQuery.multi = distance;
if(gameQuery.animation.type & $.gameQuery.ANIMATION_VERTICAL) {
gameQuery.currentFrame = 0;
this.css("background-position",""+(-distance-gameQuery.animation.offsetx)+"px "+(-gameQuery.animation.offsety)+"px");
} else if(gameQuery.animation.type & $.gameQuery.ANIMATION_HORIZONTAL) {
gameQuery.currentFrame = 0;
this.css("background-position",""+(-gameQuery.animation.offsetx)+"px "+(-distance-gameQuery.animation.offsety)+"px");
}
}
} else {
if(animation){
gameQuery.animation = animation;
gameQuery.currentFrame = 0;
if (animation.imageURL !== '') {this.css("backgroundImage", "url('"+animation.imageURL+"')");}
this.css({"background-position": ""+(-animation.offsetx)+"px "+(-animation.offsety)+"px"});
if(gameQuery.animation.type & $.gameQuery.ANIMATION_VERTICAL) {
this.css("background-repeat", "repeat-x");
} else if(gameQuery.animation.type & $.gameQuery.ANIMATION_HORIZONTAL) {
this.css("background-repeat", "repeat-y");
} else {
this.css("background-repeat", "no-repeat");
}
} else {
this.css("background-image", "");
}
}
if(callback != undefined){
this[0].gameQuery.callback = callback;
}
return this;
},
/**
* Register a callback funnction
*
* This is a non-destructive call
*
* @param {Function} fn the callback function.
* @param {Number} rate time in milliseconds between calls.
*/
registerCallback: function(fn, rate) {
$.gameQuery.resourceManager.registerCallback(fn, rate);
return this;
},
/**
* Retrieve a list of objects in collision with the subject.
*
* if 'this' is a sprite or a group, the function will retrieve the list
* of sprites (not groups) that touch it. If 'this' is the playground,
* the function will return a list of all pair of collisioning elements.
* They are represented by a jQuery object containing a series of pairs.
* Each pair represents two objects colliding.(not yet implemented)
* For now all abject are considered to be boxes.
* This IS a destructive call and should be terminated with end() to go back one level up in the chaining
*/
collision: function(filter){
var resultList = [];
//retrieve 'this' offset by looking at the parents
var itsParent = this[0].parentNode, offsetX = 0, offsetY = 0;
while (itsParent != $.gameQuery.playground[0]){
if(itsParent.gameQuery){
offsetX += itsParent.gameQuery.posx;
offsetY += itsParent.gameQuery.posy;
}
itsParent = itsParent.parentNode;
}
// retrieve the gameQuery object
var gameQuery = this[0].gameQuery;
// retrieve the playground's absolute position and size information
var pgdGeom = {top: 0, left: 0, bottom: $.playground().height(), right: $.playground().width()};