forked from techninja/ninjanode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ninjaships.node.js
executable file
·1041 lines (874 loc) · 29.1 KB
/
ninjaships.node.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
/**
* @file Ninja Ships ninjanode main serverside handler for all network
* communication to clients and turning input from clients into ship movement
*/
var _ships = {}; // all Ships are held here with the key as the user hash
var _powerUps = {}; // All free floating power up orbs are stored with a random hash key
var powerUpCount = 20;
var _pnbits = {}; // All permanent natural bodies it the sky stored just like poweups
var pnbitsCount = 20;
var _playArea = 20000; // Size of Square where users will wrap to other side
var _gameData = require('./ninjanode.gamedata.js');
// INITIALIZE THE GAME!
// Create the powerups
for (var i = 0; i < powerUpCount; i++) {
_powerUps['pu-' + Math.floor(Math.random() * 2000)] = new _powerUpObject();
}
// Create the PNBITS: Planets, suns, etc
for (var i = 0; i < pnbitsCount; i++) {
_pnbits['pn-' + Math.floor(Math.random() * 2000)] = new _pnbitsObject();
}
/**
* Exported function for creating ships
*/
module.exports.addShip = function(options){
_ships[options.id] = new _shipObject(options);
}
/**
* Exported Main loop function
*/
module.exports.processShipFrame = function(){
_updateShipMovement();
_updateProjectileMovement();
_detectCollision();
}
/**
* Exported remover for ship data
*/
module.exports.shipRemove = function(id){
if (_ships[id]){
delete _ships[id];
return true;
} else {
return false;
}
}
/**
* Exported Getter for ship data
*/
module.exports.shipGet = function(id){
if (_ships[id]){
return _ships[id];
} else {
return _ships;
}
}
/**
* Exported Getter for power up orb data
*/
module.exports.powerUpGet = function(id){
if (_powerUps[id]){
return _powerUps[id];
} else {
return _powerUps;
}
}
/**
* Exported Getter for ship types & projectiles
*/
module.exports.shipTypesGet = function(){
return {
ships: _gameData.shipTypes,
projectiles: _gameData.projectileTypes
};
}
/**
* Exported Getter for all projectile positions
*/
module.exports.getActiveProjectiles = function(){
var out = {};
// Each projectile, from each ship
for (var s in _ships){
for (var p in _ships[s].projectiles) {
var proj = _ships[s].projectiles[p];
// Only return active projectiles
if (proj.active){
out[s + '_' + p] = proj;
}
}
}
return out;
}
/**
* Exported Getter for a random starting position
*/
function getRandomPos(angleDivisibleBy){
angleDivisibleBy = angleDivisibleBy ? angleDivisibleBy : 1;
var angle = Math.floor((Math.random()*355)+1);
angle = Math.round(angle / angleDivisibleBy) * angleDivisibleBy;
var usefulArea = (_playArea / 4) * 3; // Limit spawn pos to 3/4 of the play area
return {
x: Math.floor((Math.random() * usefulArea) - (usefulArea / 2)),
y: Math.floor((Math.random() * usefulArea) - (usefulArea / 2)),
d: angle
};
}
module.exports.getRandomPos = getRandomPos;
/**
* Exported Getter for power up orbs
*/
module.exports.getPowerUps = function(){
return _powerUps;
}
/**
* Exported Getter for PNBITS
*/
module.exports.getPNBITS = function(){
return _pnbits;
}
/**
* Exported Getter for all ship positions
*/
module.exports.getAllPos = function(){
var out = {};
// Pile all the ship positions together into a clean list with a string version
for (var s in _ships){
var thrustNum = 0;
// Thrust detailing
if (!_ships[s].exploding){
if (_ships[s].thrust > 0) {
thrustNum = 1; // Forward
} else if (_ships[s].thrust < 0) {
thrustNum = 2; // Reverse
}
}
out[s] = {
pos: {
x: Math.round(_ships[s].pos.x * 100)/100,
y: Math.round(_ships[s].pos.y * 100)/100,
t: thrustNum,
d: _ships[s].pos.d
},
vel: {
x: _ships[s].velocity_x,
y: _ships[s].velocity_y,
l: _ships[s].velocityLength
}
};
out[s].str = JSON.stringify(out[s]);
}
return out;
};
/**
* Exported Setter for thrust
*/
shipSetThrust = function(id, direction){
if (_ships[id]){
var amount = _ships[id].data.accelRate;
_ships[id].thrust = amount * direction;
if (_ships[id].exploding) {
_ships[id].thrust = 0;
}
return true;
}else {
return false;
}
}
module.exports.shipSetThrust = shipSetThrust;
/**
* Exported Setter for direction
*/
shipSetTurn = function(id, direction){
if (_ships[id]){
if (direction){
_ships[id].turn = _ships[id].data.rotationSpeed * (direction == 'l' ? -1 : 1);
} else {
_ships[id].turn = 0;
}
if (_ships[id].exploding) {
_ships[id].turn = 0;
}
return true;
}else {
return false;
}
}
module.exports.shipSetTurn = shipSetTurn;
/**
* Exported Setter for thrust & direction via xy input
*/
shipSetTouch = function(id, angle){
if (_ships[id]){
if (angle !== false) {
var d = _ships[id].pos.d;
// Round incoming angle to nearest available ship rotation speed angle
// Prevents angle jitter, but makes touch less precise
angle = Math.round(angle / _ships[id].data.rotationSpeed) * _ships[id].data.rotationSpeed;
// Figure out which direction to turn comparing current angle to touch angle
var turnDir = (((angle - d + 540) % 360) - 180);
// If user touches in 40 degree range behind the ship, thrust backwards
var reverse = Math.abs(turnDir) > 150;
shipSetThrust(id, reverse ? -1 : 1);
// Same direction! disable turning
if (d == angle){
shipSetTurn(id, false);
// Stop ship calc position
_ships[id].touchAngle = false;
return true;
}
// The algorithm below fails with an angle of 0, so cheat and make it 1
if (angle == 0) {
angle = 1;
}
if (!reverse) {
if (turnDir > 0) {
shipSetTurn(id, 'r');
} else {
shipSetTurn(id, 'l');
}
}
// Continue calculation during ship move without new data sent
_ships[id].touchAngle = angle;
} else {
// Stop ship calc position
_ships[id].touchAngle = false;
shipSetTurn(id, false);
shipSetThrust(id, false);
}
return true;
}else {
return false;
}
}
module.exports.shipSetTouch = shipSetTouch;
/**
* Exported Setter for triggering Fire command
*/
module.exports.shipSetFire = function(id, createCallback, destroyCallback, weaponID){
if (_ships[id] && !_ships[id].exploding){
_ships[id].fire(createCallback, destroyCallback, weaponID);
return true;
}else {
return false;
}
}
/**
* Private ship instantiator function
* @param {object} options
* Accepts the following object keys:
* name {string}: Name of the user
* style {char}: Letter of the ship style to use (a|b|c|d|e|f)
* pos {object}: Initial position object (x:[n], y:[n], d:[n])
* hit {func}: Callback for when the ship gets hit or collides
* @returns {object} instantiated ship object
* @see module.exports.addShip
*/
function _shipObject(options){
this.name = options.name;
// Ship object state variables===========
// Velocity (speed + direction)
this.velocity_x = 0;
this.velocity_y = 0;
this.id = options.id;
this.velocityLength = 0;
this.turn = 0;
this.thrust = 0;
this.width = 64;
this.height = 64;
this.projectiles = [];
this.exploding = false;
this.powerUps = {active: [], inactive: [], list: {}, rebuild: function(){
// Rebuild the lists from scratch
this.active = [];
this.inactive = [];
for (var p in this.list) {
if (this.list[p].active) {
this.active.push(this.list[p].type.active.cssClass);
} else {
this.inactive.push(this.list[p].type.active.cssClass);
}
}
},
// Returns true if an alter function returns true, can be used to skip
// certain operations based on input
alterSkip: function(func, arg1, arg2){
for (var p in _gameData.powerUpTypes) {
if (_gameData.powerUpTypes[p].skipAlters){
if (typeof _gameData.powerUpTypes[p].skipAlters[func] == 'function') {
return _gameData.powerUpTypes[p].skipAlters[func](arg1, arg2);
}
}
}
return false;
},
// Returns a value if an alter function returns a value, default value otherwise
alter: function(func, def, arg1, arg2){
for (var p in _gameData.powerUpTypes) {
if (_gameData.powerUpTypes[p].alters){
if (typeof _gameData.powerUpTypes[p].alters[func] == 'function') {
return _gameData.powerUpTypes[p].alters[func](def, arg1, arg2);
}
}
}
return def;
}
};
// Default to style 'a' if not found in shipTypes
this.style = _gameData.shipTypes[options.style] ? options.style : 'a';
// All customizable ship type options are held here
this.data = _gameData.shipTypes[this.style];
// Set intial shield power level (will be drawn down by hits from opponents)
this.shieldPowerStatus = this.data.shield.max;
// Populate weapons with projectile type data for data access
for (var w in this.data.weapons){
this.data.weapons[w].data = _gameData.projectileTypes[this.data.weapons[w].type];
}
this.pos = options.pos ? options.pos : getRandomPos(this.data.rotationSpeed);
// FUNCTION Direct visual rotation
this.rot = function(deg){
this.pos.d = this.pos.d + deg;
if (this.pos.d >= 360) {
this.pos.d = 0;
}else if (this.pos.d <= 0) {
this.pos.d = 360;
}
};
// Prep the lastFire var for testing
this.lastFire = [0, 0];
// FUNCTION Send out a projectile
this.fire = function(createCallback, destroyCallback, weaponID){
// Don't fire too quickly! Respect the fireRate for this ship
if (new Date().getTime() - this.lastFire[weaponID] < this.data.weapons[weaponID].fireRate){
return;
}
this.lastFire[weaponID] = new Date().getTime();
var fireCount = this.powerUps.alter('fire_count', 1, this);
switch (fireCount) {
case 1:
addProjectile(this, this.pos.d);
break;
case 3:
addProjectile(this, this.pos.d - 10);
addProjectile(this, this.pos.d);
addProjectile(this, this.pos.d + 10);
break;
}
function addProjectile(ship, angle) {
// Add to the projectile array for the ship object
var index = -1;
// Cull the array position of the first non-active projectile
for (var i in this.projectiles){
if (!ship.projectiles[i].active){
index = i;
break;
}
}
// If there are nor projectiles, or they're all active, then
// index should be added to the end (AKA, array length!)
if (index == -1) {
index = ship.projectiles.length;
}
ship.projectiles[index] = new _projectileObject({
id: index,
type: ship.data.weapons[weaponID].type,
style: ship.data.weapons[weaponID].style,
shipID: ship.id,
weaponID: weaponID,
pos: {x: ship.pos.x + ship.width/2, y: ship.pos.y + ship.height/2, d: angle},
create: createCallback,
destroy: destroyCallback
});
}
}
// FUNCTION remove velocity helper
this.kill_velocity = function(){
this.velocity_x = 0;
this.velocity_y = 0;
this.velocityLength = 0;
}
// FUNCTION projectile hit/collision callback
this.hit = function(data){
data.target = this;
if (data.type == 'collision'){
// Same shield, both die
if (data.target.shieldPowerStatus == data.source.shieldPowerStatus) {
data.target.shieldPowerStatus = 0;
data.source.shieldPowerStatus = 0;
} else {
// Force shield comparison, whoever wins gets only 5 shield points left
data.target.shieldPowerStatus -= data.source.shieldPowerStatus;
data.source.shieldPowerStatus -= data.target.shieldPowerStatus + 15;
}
if (data.target.shieldPowerStatus > 0) {
// Only leave them with a sliver if they lived
data.target.shieldPowerStatus = 5;
} else { // Kill em if their shield is out
data.target.shieldPowerStatus = 0;
data.target.triggerBoom();
}
if (data.source.shieldPowerStatus > 0) {
// Only leave them with a sliver if they lived
data.source.shieldPowerStatus = 5;
} else {
options.hit({
type: 'secondary collision',
target: data.source
});
data.source.shieldPowerStatus = 0;
data.source.triggerBoom();
}
} else if (data.type == 'projectile') {
// Remove the shield power directly via the weapon damage
data.target.shieldPowerStatus = data.target.shieldPowerStatus - data.weapon.data.damage;
// Kill em if their shield is out
if (data.target.shieldPowerStatus <= 0) {
data.target.shieldPowerStatus = 0;
data.target.triggerBoom();
}
} else if (data.type == 'pnbcollision') {
// Target hit source (A permanent natural body!)
data.target.shieldPowerStatus -= 50;
// Kill em if their shield is out
if (data.target.shieldPowerStatus <= 0) {
data.target.shieldPowerStatus = 0;
data.target.triggerBoom();
}
}
options.hit(data);
}
// FUNCTION Trigger ship explosion
this.triggerBoom = function(){
if (!this.exploding){
var ship = this;
ship.exploding = true;
// Clear out any powerups when you die
for (var p in ship.powerUps.list) {
if (ship.powerUps.list[p].active) {
ship.powerUps.list[p].active = false;
clearInterval(ship.powerUps.list[p].interval);
}
}
ship.powerUps.rebuild();
// Trigger first callback
options.boom({
id: ship.id,
stage: 'start'
});
// 2 seconds to wait for the middle
setTimeout(function(){
// Trigger second callback
options.boom({
id: ship.id,
stage: 'middle'
});
}, 300)
// 5 seconds should be enough time for the explosion and wait
// Respawn & reset ship
setTimeout(function(){
ship.kill_velocity();
ship.pos = getRandomPos(ship.data.rotationSpeed);
ship.exploding = false;
ship.shieldPowerStatus = ship.data.shield.max;
// Trigger third callback
options.boom({
id: ship.id,
stage: 'complete'
});
}, 5500)
}
}
}
/**
* Private projectile instantiator function
* @param {object} options
* Requires the following object keys:
* type {string}: Type of projectile, currently supports (laser|energy)
* style {string}: Class/Color for projectile
* pos {object}: Starting position object (x:[n], y:[n], d:[n])
* id {integer}: The serial index ID for this projectile
* create {func}: Callback called when projectile is created
* destroy {func}: Callback called when projectile is destroyed
* @returns {object} instantiated projectile object
* @see _shipObject.fire
*/
function _projectileObject(options){
this.pos = options.pos;
this.style = options.style;
this.id = options.id;
this.shipID = options.shipID;
this.age = 0;
this.type = options.type;
this.weaponID = options.weaponID;
this.born = new Date().getTime();
this.data = _gameData.projectileTypes[options.type];
this.pos.x = this.pos.x - this.data.size.width/2;
this.pos.y = this.pos.y - this.data.size.height/2;
this.destroy = function(){
this.active = false;
options.destroy(this);
}
this.active = true;
options.create(this);
}
/**
* Private projectile calculator. Moves all projectiles for all ships
* @see module.exports.processShipFrame
*/
function _updateProjectileMovement(){
for(var s in _ships) {
for(var p in _ships[s].projectiles) {
var proj = _ships[s].projectiles[p];
if (proj.active){
var theta = proj.pos.d * (Math.PI / 180);
proj.pos.x+= Math.sin(theta) * proj.data.speed;
proj.pos.y+= Math.cos(theta) * -proj.data.speed;
// Projectile is to old! Kill it.
if (new Date().getTime() - proj.born > proj.data.life) {
proj.destroy();
}
}
}
}
}
/**
* Private powerUp instantiator function
* @param {object} options
* Accepts the following object keys:
* type {string}: specific type of power up to create
* @returns {object} instantiated power up object
* @see module.exports.addPowerUp
*/
function _powerUpObject(options){
var powerUps = _gameData.powerUpTypes;
if (!options) options = {};
// Take in passed type value
if (options.type && powerUps[options.type]) {
this.type = powerUps[options.type];
} else { // Pick one at random~
this.type = _getWeightedRandomItem(powerUps);
}
// Power up object state variables===========
this.id = this.type.id;
this.pos = options.pos ? options.pos : getRandomPos();
delete this.pos.d; // Don't need the rotation
this.visible = true;
// Activate the powerup for a given ship! ===================================
this.activate = function(ship) {
this.visible = false;
var pType = this.id;
// has this user seen this powerup before?
if (ship.powerUps.list[pType] && ship.powerUps.list[pType].active) {
ship.powerUps.list[pType].counter += this.type.active.time; // Add to the time
} else {
ship.powerUps.list[pType] = {
counter: this.type.active.time,
active: true,
type: this.type,
interval: setInterval(function(){
ship.powerUps.list[pType].counter--;
if (ship.powerUps.list[pType].counter <= 0) {
ship.powerUps.list[pType].active = false;
clearInterval(ship.powerUps.list[pType].interval);
ship.powerUps.rebuild();
}
}, 1000)
}
}
ship.powerUps.rebuild();
// Time till the power up orb respawns
setTimeout(function(powerUp){
powerUp.visible = true;
// TODO: randomize position?
}, this.type.respawnTime * 1000, this);
}
}
/**
* Private PNBITS (celestial object) instantiator function
* @param {object} options
* Accepts the following object keys:
* (N/A for the moment)
* @returns {object} instantiated pnbits object
*/
function _pnbitsObject(options){
var pnbits = _gameData.pnbitsTypes;
if (!options) options = {};
// Pick one at random based on rarity
this.type = _getWeightedRandomItem(pnbits);
// PNBITS state variables===========
this.id = this.type.id;
this.pos = options.pos ? options.pos : getRandomPos();
this.visible = true;
this.radius = Math.round(_rand(this.type.ranges.radius));
this.density = _rand(this.type.ranges.density);
this.center = {x: this.pos.x + this.radius, y: this.pos.y + this.radius};
this.g = (this.density * this.radius)^2 / 10000000;
this.name = "a type " + this.type.minor.toUpperCase() + ' ' + this.type.major;
}
/**
* Private collision detector. Detects collisions between ships, projectiles,
* powerups, obstacles and the rest. Currently very broken.
* @see module.exports.processShipFrame
*/
function _detectCollision(){
// Loop through every ship, to every ship, to every projectile
for(var s in _ships){
var source = _ships[s];
// Check for ship intersection with a power up!
if (!source.exploding) { // Ship can't be exploding...'
for(var p in _powerUps) {
var pow = _powerUps[p];
if (pow.visible) { // Only currently visible powerups
if (_circleIntersects(source.pos, source.width/2, pow.pos, pow.type.size/2)){
pow.activate(source);
}
}
}
}
// Check for ship intersection with a celestial body!
if (!source.exploding) { // Ship can't be exploding...'
for(var p in _pnbits) {
var pnb = _pnbits[p];
if (_circleIntersects(source.pos, source.width/2, pnb.pos, pnb.radius)){
console.log(source.name + ' slammed into a type ' + pnb.type.minor + ' ' + pnb.type.major);
source.hit({type: 'pnbcollision', source: pnb});
}
}
}
// Check for projectile intersection with a celestial body!
for (var i in source.projectiles){
var p = source.projectiles[i];
if (p.active){ // Skip inactive projectiles
// Have projectiles hit PNBITS
for(var x in _pnbits) {
var pnb = _pnbits[x];
if (_circleIntersects({x: p.pos.x, y: p.pos.y - p.data.yOffset}, p.data.size.hitRadius, pnb.pos, pnb.radius)){
p.destroy();
break;
}
}
}
}
// Check every ship against this projectile
for(var t in _ships){
var target = _ships[t];
if (t != s && !target.exploding && source.powerUps.alterSkip('collision_ship2projectile', source, target) !== true){ // Ships can't hit themselves
// Exploding ships can't collide with things
if (!source.exploding){
skipcollision = source.powerUps.alterSkip('collision_ship2ship', source, target) === true;
// While we're here, check for ship to ship collision via circular hitbox
if (_circleIntersects(source.pos, source.width/2, target.pos, target.width/2) && !skipcollision){
// Trigger hit callback (to simplify things.. both should die
if (target.velocityLength > source.velocityLength){
console.log(target.name + ' slammed into ' + source.name);
source.hit({
type: 'collision',
source: target // Include source to find out who's hitting who
});
} else {
console.log(source.name + ' slammed into ' + target.name);
target.hit({
type: 'collision',
source: source // Include source to find out who's hitting who
});
}
} // End Check Circle Intersection
} // End not source exploding
// Loop through projectiles on source ship (CAN be exploding!)
for (var i in source.projectiles){
var p = source.projectiles[i];
if (p.active){ // Skip inactive projectiles
if (_circleIntersects({x: p.pos.x, y: p.pos.y - p.data.yOffset}, p.data.size.hitRadius, target.pos, target.width/2)){
// Target is within the hit circle fpr projectile! check horizontal
console.log(source.name + ' shot ' + target.name);
// Run hit callback on the target, the shooter is the source
target.hit({
type: 'projectile',
weapon: p,
source: source
});
// Register knockback on the target on next move
target.knockBack = {
angle: p.pos.d,
amount: p.data.knockBackForce
};
p.destroy();
} // End Check Circular Intersection
} // End if projectile active
} // End each projectile in source ship
} // End if source != target
} // End each target ship
} // End Each source ship
}
// Find out if two circles intersect for hit detection
function _circleIntersects(pos1, radius1, pos2, radius2){
// Get center of circles (as positions are all top left corner centered)
var x0 = pos1.x + radius1;
var y0 = pos1.y + radius1;
var x1 = pos2.x + radius2;
var y1 = pos2.y + radius2;
// Find the distance between the centerpoints
// TODO: Probably use something faster than sqrt...
var distance = Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
// If the distance between them is less than the radius, it's inside!
if (distance < radius2) {
return true;
}
// Return true if the distance is shorter than difference between the radii
if (distance >= (radius1 + radius2) || distance <= Math.abs(radius1 - radius2)){
return false;
} else {
return true;
}
}
/**
* Private ship calculator. Moves all ships individually based on inertia
* @see module.exports.processShipFrame
*/
function _updateShipMovement(){
for (s in _ships){
var self = _ships[s];
// Process touch angle movement, if any
if (self.touchAngle) {
shipSetTouch(s, self.touchAngle);
}
// Rotate the ship
if (self.turn != 0 && !self.exploding){
self.rot(self.turn);
}
// Apply shield regeneration
if (!self.exploding) {
self.shieldPowerStatus = self.shieldPowerStatus + self.data.shield.regenRate;
// Cap shield power at max power
if (self.shieldPowerStatus > self.data.shield.max){
self.shieldPowerStatus = self.data.shield.max;
}
}
// Apply thrust vector
if (self.thrust != 0 || self.hit){
var angle = self.pos.d;
var amount = self.thrust;
// For knockback hit, only run once..
if (self.knockBack){
angle = self.knockBack.angle;
amount = self.knockBack.amount;
delete self.knockBack;
}
theta = angle * (Math.PI / 180);
self.velocity_x += Math.cos(theta) * -amount;
self.velocity_y += Math.sin(theta) * amount;
}
// Modify Velocity length/angle based on proximity to all PNBITS
var pnbitsEffected = false;
if (!self.exploding) {
for (var i in _pnbits) {
var p = _pnbits[i];
var selfCenter = {x: self.pos.x + self.width/2, y: self.pos.y + self.height/2};
var distance = _lineDistance(selfCenter, p.center) - self.width/2;
// Only apply gravitational effects within the "effective area" of the object
if (distance < p.density * p.radius * 5) {
// Find the angle between the ship and the center of the mass
var theta = _lineAngle(self.pos, p.center);
var shipMass = 100;
pnbitsEffected = true;
// Calculate amount of gravitational pull as log of distance and mass
var amount = ((p.g * shipMass / distance ^ 2) / 300);
theta = theta - (Math.PI / 2); // Rotate angle 90 degrees
// Apply gravitational pull to vector
self.velocity_x += Math.cos(theta) * amount;
self.velocity_y += Math.sin(theta) * amount;
}
}
}
// Find the overall velocity length
var dragOption = pnbitsEffected ? 0 : self.data.drag;
self.velocityLength = Math.sqrt(Math.pow(self.velocity_x, 2) + Math.pow(self.velocity_y, 2)) - dragOption;
// if exploding, exponential drag!
if (self.exploding){
self.velocityLength = self.velocityLength / 1.1;
}
if (self.velocityLength < 0) {
self.velocityLength = 0;
} else {
if (self.velocityLength > self.data.topSpeed && !pnbitsEffected){
self.velocityLength = self.data.topSpeed;
}
// find the current velocity rotation
var rot = Math.atan2(self.velocity_y, self.velocity_x) * (180 / Math.PI);
// recalculate the velocities by multiplying the new rotation by the overall velocity length
var theta = rot * (Math.PI / 180);
self.velocity_x = Math.cos(theta) * self.velocityLength;
self.velocity_y = Math.sin(theta) * self.velocityLength;
// update position
self.pos.y += self.velocity_x;
self.pos.x += self.velocity_y;
// Wrap to Play Area (centered on zero)
var p = _playArea / 2;
if (self.pos.y < -p){self.pos.y = p} // Top to bottom
if (self.pos.y > p){self.pos.y = -p} // Bottom to top
if (self.pos.x < -p){self.pos.x = p} // Left to right
if (self.pos.x > p){self.pos.x = -p} // Right to left
}
}
}
/**
* Private utility function get angle of the line between two points
* @param {object} point1
* X, Y coordinate object of first point
* @param {object} point2
* X, Y coordinate object of second point
* @returns {float} Angle in absolute radians
*/
function _lineAngle(point1, point2) {
var theta = Math.atan2(-(point1.y - point2.y), (point1.x - point2.x));
if (theta < 0) theta += 2 * Math.PI;
return theta;
}
/**
* Private utility function get distance between two points
* @param {object} point1
* X, Y coordinate object of first point
* @param {object} point2
* X, Y coordinate object of second point
* @returns {float} distance between first and second point
*/
function _lineDistance(point1, point2) {
var xs = 0;
var ys = 0;
xs = point2.x - point1.x;
xs = xs * xs;
ys = point2.y - point1.y;
ys = ys * ys;
return Math.sqrt( xs + ys );
}
/**
* Private utility function to get a random within a min/max
* @param {int} || {array} min
* Lowest allowed value, or array of min/max
* @param {int} max
* Highest allowed value
* @returns {float} value between min and max