-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
1220 lines (1158 loc) · 52.8 KB
/
game.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
let canvas = document.querySelector("#canvas");
let ctx = canvas.getContext("2d");
canvas.style.width = window.innerWidth + "px";
canvas.style.height = window.innerHeight + "px";
let canvasDivision = 3;
if (ctx.roundRect === undefined) ctx.roundRect = ctx.rect;
let [cos, sin] = [Math.cos.bind(Math), Math.sin.bind(Math)];
let gameState = "menu";
let enemyVel = null, playerVel = null, rollSpeed = null, pitchSpeed = null, enemyRollSpeed = null, enemyPitchSpeed = null, aimAssistRange = null, playerRadius = null, hp = null, enemyHP = null, pain = null, gravity = null, jumpSpeed = null, step = null, accelFactor = null, FOV = null, trueFOV = null, cameraDistance = null, bloom = null, weaponTraits = null, aimFactor = null, gun = null, recoil = null, shotCooldown = null, sway = null, reloading = null, reloadTime = null, enemyBloom = null, enemyShotChance = null, hitShot = null, enemyDamage = null, frameBounds = null, showCrosshair = null, showAmmo = null, showHP = null, showFPS = null, showHits = null, mouseMovement = null, equipTimer = null;
let bulletVel = null;
let mapBoundaries = null;
let gameActive = false;
let player = null, enemy = null, map = null, fire = null, pistol = null, smg = null, shotgun = null, sniper = null;
function resetValues() {
enemyVel = 1.5; playerVel = [0, 0, 0]; rollSpeed = 0.1; pitchSpeed = 0.04; enemyRollSpeed = 0.07; enemyPitchSpeed = 0.035; aimAssistRange = Math.PI/24; bulletVel = 5; playerRadius = 1.5; hp = 100; enemyHP = 100; pain = 0; showCrosshair = true; showAmmo = true; showHP = true; showFPS = true; showHits = true;
jumpSpeed = 1.5; gravity = .4, step = 0.1; accelFactor = 1.2; trueFOV = FOV = [/*Math.PI/1.7*/2.012742, Math.PI/2.2]; cameraDistance = 0; bloom = Math.PI/10; aimFactor = 0; recoil = 0; shotCooldown = 0; sway = 0; reloading = false; reloadTime = 0; enemyBloom = Math.PI/25; enemyShotChance = .1; enemyDamage = 10; frameBounds = [11, 14]; mouseMovement = [0, 0]; equipTimer = 0;
hitShot = {state: 1, frames: 0};
shapes = []; bullets = []; enemies = []; lasers = [];
player = copyShape(playerTemplate); player.move([0, 2, 4]); if (cameraDistance > 0) shapes.push(player);
map = copyShape(mapTemplate); shapes.push(map);
for (let i = 0; i < map.polys.length; i++) {
let poly = map.polys[i];
if (poly.mtl === "EnemySpawn") {
if (Math.random() < .7) spawnEnemy(center(poly));
map.polys.splice(i, 1);
i -= 1;
}
}
fire = copyShape(fireTemplate);
pistol = copyShape(pistolTemplate); pistol.viewmodel = true; shapes.push(pistol);
smg = copyShape(smgTemplate); smg.viewmodel = true;
shotgun = copyShape(shotgunTemplate); shotgun.viewmodel = true;
sniper = copyShape(sniperTemplate); sniper.viewmodel = true;
gun = pistol;
weaponTraits = new Map();
weaponTraits.set(pistol, {
name: "Pistol",
automatic: false,
runningBloom: 1.5,
defaultBloom: Math.PI/50,
normalPos: [-1.2, -.5, 2.5],
aimPos: [0, -.24, 2],
recoil: 1,
damage: 20,
cooldown: 2,
slot: 1,
ammo: 20,
totalAmmo: 20,
reloadTime: 40,
});
weaponTraits.set(smg, {
name: "SMG",
automatic: true,
runningBloom: .5,
defaultBloom: Math.PI/120,
normalPos: [-2, -1, 3],
aimPos: [0, -.79, 2.5],
recoil: .5,
damage: 12,
cooldown: 2,
fovFactor: .5,
slot: 2,
ammo: 30,
totalAmmo: 30,
reloadTime: 40,
});
weaponTraits.set(shotgun, {
name: "Shotgun",
automatic: true,
runningBloom: 0.2,
defaultBloom: 0*Math.PI/70,
normalPos: [-3, -1.5, 11],
aimPos: [0, -.9, 6],
recoil: 10,
damage: 15,
cooldown: 15,
shots: 7,
spread: Math.PI/30,
slot: 3,
ammo: 8,
totalAmmo: 8,
reloadTime: 20,
reloadPerShot: true,
});
weaponTraits.set(sniper, {
name: "Sniper",
automatic: false,
runningBloom: 3,
defaultBloom: 0*Math.PI/200,
normalPos: [-3, -2, 7],
aimPos: [0, -1.57, 8],
recoil: 5,
damage: 70,
cooldown: 30,
fovFactor: .22,
slot: 4,
ammo: 1,
totalAmmo: 1,
reloadTime: 60,
});
//enemy.update(Math.PI, "yaw");
//shapes.push(enemy);
mapBoundaries = [Math.max(...map.polys.map(poly => Math.max(...poly.map(pt => pt[0])))),
Math.min(...map.polys.map(poly => Math.min(...poly.map(pt => pt[0])))),
Math.max(...map.polys.map(poly => Math.max(...poly.map(pt => pt[2])))),
Math.min(...map.polys.map(poly => Math.min(...poly.map(pt => pt[2])))),
Math.max(...map.polys.map(poly => Math.max(...poly.map(pt => pt[1]))))];
gameActive = true;
camAngle = [0, 0];
}
function mapWhilePreserve(list, fn) {
for (let i = 0; i < list.length; i++) {
list[i] = fn(list[i]);
}
return list;
}
function interpolateDepth(d1, d2, distAlong, fullDist) {
return (d2-d1)*(distAlong/fullDist)+d1;
}
//the following functions use a custom rasterizer and a zbuffer for rendering, see the following:
//https://en.wikipedia.org/wiki/Z-buffering
//http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html
//https://stackoverflow.com/a/8290734/15938577
function drawPixel(canvasData, depthBuffer, x, y, r, g, b, depth, viewmodelBuffer, viewmodel=false) {
if (x < 0 || x >= canvas.width || y < 0 || y > canvas.height) return;
var index = (x + y * canvas.width) * 4;
if ((((!viewmodel)||viewmodelBuffer[index]) && (depthBuffer[index] !== undefined && depthBuffer[index] < depth)) || (viewmodelBuffer[index]===true && !viewmodel) || depth < 0) return;
depthBuffer[index] = depth;
if (viewmodel) viewmodelBuffer[index] = true;
let fogIncrease = 3*Math.sqrt(Math.min(depth, 500));
canvasData.data[index + 0] = Math.min(r + fogIncrease, 255);
canvasData.data[index + 1] = Math.min(g + fogIncrease, 255);
canvasData.data[index + 2] = Math.min(b + fogIncrease, 255);
canvasData.data[index + 3] = 255;
}
function drawTopTri(p1, p2, p3, canvasData, depthBuffer, mtl, viewmodelBuffer, viewmodel=false) {
let slope1 = (p2[0]-p1[0])/(p2[1]-p1[1]);
let slope2 = (p3[0]-p1[0])/(p3[1]-p1[1]);
let switched = slope1 > slope2;
if (switched) [slope1, slope2] = [slope2, slope1];
let curXs = [p1[0], p1[0]];
let depths = [p1.depth, p1.depth];
if (p1[1] < 0) curXs = [curXs[0]+slope1*-p1[1], curXs[1]+slope2*-p1[1]];
for (let y = Math.max(0, (p1[1])); y <= Math.min(canvas.height, p2[1]); y++) {
if (y >= 0 && y <= canvas.height) {
for (let x = Math.max(Math.floor(curXs[0]), 0); x <= Math.min(curXs[1], canvas.width); x++) {
drawPixel(canvasData, depthBuffer, Math.round(x), Math.floor(y), mtl[0], mtl[1], mtl[2],
1/(curXs[1] === curXs[0] ? depths[0] : interpolateDepth(depths[0], depths[1], x-curXs[0], curXs[1]-curXs[0])), viewmodelBuffer, viewmodel
);
}
depths = [interpolateDepth(p1.depth, p2.depth, y - (p1[1]), p2[1]-(p1[1])),
interpolateDepth(p1.depth, p3.depth, y - (p1[1]), p3[1]-(p1[1]))];
if (switched) depths = [depths[1], depths[0]];
}
curXs[0] += slope1;
curXs[1] += slope2;
}
}
function drawBottomTri(p1, p2, p3, canvasData, depthBuffer, mtl, viewmodelBuffer, viewmodel=false) {
let slope1 = (p2[0]-p1[0])/(p2[1]-p1[1]);
let slope2 = (p3[0]-p1[0])/(p3[1]-p1[1]);
let switched = slope1 < slope2;
if (switched) [slope1, slope2] = [slope2, slope1];
let curXs = [p1[0], p1[0]];
let depths = [p1.depth, p1.depth];
if (p1[1] < 0) curXs = [curXs[0]+slope1*-p1[1], curXs[1]+slope2*-p1[1]];
for (let y = Math.max((p1[1]), 0); y >= Math.max(0, p2[1]); y--) {
if (y >= 0 && y <= canvas.height) {
if (curXs[1]-curXs[0]>=2) {
for (let x = Math.max((curXs[0]), 0); x <= Math.min(curXs[1], canvas.width); x++) {
drawPixel(canvasData, depthBuffer, Math.round(x), Math.round(y), mtl[0], mtl[1], mtl[2],
1/(curXs[1] === curXs[0] ? depths[0] : interpolateDepth(depths[0], depths[1], x-curXs[0], curXs[1]-curXs[0])), viewmodelBuffer, viewmodel
);
}
}
depths = [interpolateDepth(p1.depth, p2.depth, y - (p1[1]), p2[1]-(p1[1])),
interpolateDepth(p1.depth, p3.depth, y - (p1[1]), p3[1]-(p1[1]))];
if (switched) depths = [depths[1], depths[0]];
}
curXs[0] -= slope1;
curXs[1] -= slope2;
}
}
function drawTri(p1, p2, p3, canvasData, depthBuffer, mtl, viewmodelBuffer, viewmodel=false) {
let pts = [p1, p2, p3].map(pt => mapWhilePreserve(pt, Math.round));
if (pts.some(pt => pt.some(n => Number.isNaN(n)||!Number.isFinite(n)))) return;
let ptOutsideList = [];
for (let pt of pts) {
let outside = [];
if (pt[0] < 0) outside.push(1);
if (pt[0] > canvas.width) outside.push(2);
if (pt[1] < 0) outside.push(3);
if (pt[1] > canvas.height) outside.push(4);
ptOutsideList.push(outside)
}
if (ptOutsideList.every(outside => outside.length > 0) && ptOutsideList.every(outside => outside.every(location => ptOutsideList.every(list => list.includes(location))))) return;
pts.sort((a, b) => a[1]-b[1]);
if (pts[1][1] === pts[2][1]) {drawTopTri(pts[0], pts[1], pts[2], canvasData, depthBuffer, mtl, viewmodelBuffer, viewmodel);return;}
if (pts[0][1] === pts[1][1]) {drawBottomTri(pts[2], pts[1], pts[0], canvasData, depthBuffer, mtl, viewmodelBuffer, viewmodel);return;}
let p4 = [pts[0][0] + ((pts[1][1] - pts[0][1]) / (pts[2][1] - pts[0][1])) * (pts[2][0] - pts[0][0]), pts[1][1]];
p4.depth = interpolateDepth(pts[0].depth, pts[2].depth, p4[1]-pts[0][1], pts[2][1]-pts[0][1]);
drawTopTri(pts[0], pts[1], p4, canvasData, depthBuffer, mtl, viewmodelBuffer, viewmodel);
drawBottomTri(pts[2], p4, pts[1], canvasData, depthBuffer, mtl, viewmodelBuffer, viewmodel);
}
function drawPoly(pts, canvasData, depthBuffer, mtl, viewmodelBuffer, viewmodel=false) {
for (let i = 0; i < pts.length-2; i++) {
drawTri(pts[0], pts[i+1], pts[i+2], canvasData, depthBuffer, mtl, viewmodelBuffer, viewmodel);
}
}
class matrix {
constructor(list) {
this.list = list;
this.dim = [this.list.length, this.list[0].length];
}
multiply(other) {
if (other.dim[0] !== this.dim[1]) return false;
let newMatrix = matrix.dimensions(this.dim[0], other.dim[1]);
for (let i = 0; i < this.dim[0]; i++) {
for (let j = 0; j < other.dim[1]; j++) {
newMatrix.list[i][j] = this.list[i].map((el, idx) => el*other.list[idx][j]).reduce((a, b)=>a+b);
}
}
return newMatrix;
}
static from(list) {return new matrix(list);}
static dimensions(r, c) {
let list = [];
for (let i = 0; i < r; i++) {
list.push((new Array(c)).fill(0));
}
return new matrix(list);
}
static identity(n) {
let list = [];
for (let i = 0; i < n; i++) {
list.push([]);
for (let j = 0; j < n; j++) {
if (i === j) list.at(-1).push(1);
else list.at(-1).push(0);
}
}
return new matrix(list);
}
}
//a custom class for 3d objects that allows movement and rotation
class Shape {
constructor(polys) {
this.polys = polys;
this.offset = [0, 0, 0];
this.rotate = [0, 0, 0];
this.speed = 0;
this.rotatedPolys = null;
}
move(offset) {
this.offset = this.offset.map((el, idx) => el+offset[idx]);
this.polys = this.polys.map(poly => {
let newPoly = poly.map(pt => pt.map((el, idx) => Number(el)+offset[idx]));
newPoly.mtl = poly.mtl;
newPoly.cross = poly.cross;
return newPoly;
});
if (this.rotatedPolys !== null) {
this.rotatedPolys = this.rotatedPolys.map(poly => {
let newPoly = poly.map(pt => pt.map((el, idx) => Number(el)+offset[idx]));
newPoly.mtl = poly.mtl;
newPoly.cross = poly.cross;
return newPoly;
});
}
}
moveInDirection(dist) {
this.move(times(vecFromAngle(this.rotate), dist));
}
turn(direction) {
this.rotate = this.rotate.map((n, idx) => n + direction[idx]);
direction = this.rotate;
let rotationX = matrix.from([[Math.cos(direction[2]), -Math.sin(direction[2]), 0], [Math.sin(direction[2]), Math.cos(direction[2]), 0], [0, 0, 1]]);
let rotationY = matrix.from([[Math.cos(direction[0]), 0, Math.sin(-direction[0])], [0, 1, 0], [Math.sin(direction[0]), 0, Math.cos(direction[0])]]);
let rotationZ = matrix.from([[1, 0, 0], [0, Math.cos(-direction[1]), -Math.sin(-direction[1])], [0, Math.sin(-direction[1]), Math.cos(-direction[1])]]);
let fullRotation = rotationY.multiply(rotationZ).multiply(rotationX);
this.rotatedPolys = this.polys.map(poly => {
let pts = poly.map(pt => [[pt[0]-this.offset[0]], [pt[1]-this.offset[1]], [pt[2]-this.offset[2]]]);
pts = pts.map(pt => (fullRotation.multiply(matrix.from(pt)).list));
pts = pts.map(pt => [[Number(pt[0][0]+this.offset[0])], [Number(pt[1][0]+this.offset[1])], [Number(pt[2][0]+this.offset[2])]]);
let newPoly = pts;
newPoly.mtl = poly.mtl;
return newPoly;
});
this.updateCrossProducts(true);
}
resetTurn() {
this.rotatedPolys = null;
this.rotate = [0, 0, 0];
}
updateCrossProducts(rotated=false) {
for (let poly of rotated ? this.rotatedPolys : this.polys) {
poly.cross = crossPoly(poly);
}
}
}
//a lot of utility functions that were created out of necessity
function crossProduct(vec1, vec2) {
return (matrix.from([[0, -vec1[2], vec1[1]], [vec1[2], 0, -vec1[0]], [-vec1[1], vec1[0], 0]])).multiply(matrix.from([[vec2[0]], [vec2[1]], [vec2[2]]]));
}
function crossPoly(pts) {
return unit(crossProduct([pts[1][0]-pts[0][0], pts[1][1]-pts[0][1], pts[1][2]-pts[0][2]], [pts[2][0]-pts[1][0], pts[2][1]-pts[1][1], pts[2][2]-pts[1][2]]).list.flat());
}
function dotProduct(vec1, vec2) {
return vec1.reduce((a, b, idx) => a+b*vec2[idx], 0);
}
function plus(pt1, pt2) {
return pt1.map((n, idx) => n+pt2[idx]);
}
function minus(pt1, pt2) {
return pt1.map((n, idx) => n-pt2[idx]);
}
function times(pt1, x) {
return pt1.map((n) => n*x);
}
function angleBetween(pt1, center, pt2) {
return Math.acos(dotProduct(unit(minus(pt1, center)), unit(minus(pt2, center))))
}
function center(list) {
return list.reduce((a, b) => a.map((el, idx) => el+b[idx]/list.length), [0,0,0]);
}
function unit(list) {
let dist = list.reduce((a, b) => a+b**2, 0)**0.5;
if (dist === 0) return list;
return list.map(n => n/dist);
}
function distance(pt1, pt2) {
if (pt2 === undefined) pt2 = [];
return Math.sqrt(pt1.map((n, idx) => (n-(pt2[idx]||0))**2).reduce((a, b) => a+b));
}
function vecFromAngle(angle) {
return [-Math.sin(angle[0])*Math.cos(angle[1]), Math.sin(angle[1]), Math.cos(angle[0])*Math.cos(angle[1])];
}
function deviate(angle, bloom) {
let bloomAngle = Math.random()*2*Math.PI, bloomWidth = (Math.random()-.5)*bloom;
return [angle[0] + Math.cos(bloomAngle)*bloomWidth/(Math.abs(Math.cos(camAngle[1]))),
angle[1] + Math.sin(bloomAngle)*bloomWidth];
}
function leadAim(initPos, targetPos, speed, targetVel) {
let collisionPos = targetPos, time = null;
for (let i = 0; i < 5; i++) {
time = Math.sqrt(collisionPos.map((n, idx) => (n-initPos[idx])**2).reduce((a, b) => a+b))/speed;
collisionPos = targetPos.map((n, idx) => n+targetVel[idx]*time);
}
return [unit(collisionPos.map((n, idx) => n-initPos[idx])), collisionPos];
}
function distInDir(dirVec, init, pt) {
if (init === null) init = [0, 0, 0];
return dotProduct(unit(dirVec), pt.map((n, idx) => n-init[idx]));
}
//this function is the basis for all of the bullet and physics collisions - detect flat circle/3d tri collision
//assuming the circle and triangle are coplanar
//3 steps: 1, check if the point is within the triangle. 2, check if the radius is outside the triangle but the circle touches a vertex. 3, check if the radius is outside the triangle but the circle touches an edge
function ptHitsTri(pt, radius, tri, data) {
if (data === undefined) data = {};
let centroid = center(tri);
let dist = Math.max(...tri.map(pt => distance(pt, centroid)));
if (dist+radius < distance(pt, centroid)) return false;
let firstpoint = tri.reduce((a, b) => angleBetween(a, centroid, pt) < angleBetween(b, centroid, pt) ? a : b);
let previous = tri.at(tri.indexOf(firstpoint)-1);
if (Math.abs(angleBetween(previous, centroid, firstpoint) - (angleBetween(previous, centroid, pt)+angleBetween(pt, centroid, firstpoint))) < 0.001) {
secondpoint = previous;
} else {
secondpoint = tri.at(tri.indexOf(firstpoint)+1-tri.length);
}
let expectedDistance = Math.sin(angleBetween(centroid, firstpoint, secondpoint))*distance(centroid, firstpoint) / Math.sin(Math.PI-angleBetween(firstpoint, centroid, pt)-angleBetween(centroid, firstpoint, secondpoint));
if (distance(centroid, pt) <= expectedDistance) {
return data["vec"] ? times(data["poly"].cross, distInDir(data["poly"].cross, center(data["poly"]), data["sphereCenter"]) > 0 ? step : -step) : true;
}
if (radius === 0) return false;
let distAlongSide = dotProduct(unit(minus(secondpoint, firstpoint)), minus(pt, firstpoint));
if (distAlongSide < 0) {
if (distance(firstpoint, pt) <= radius) return data["vec"] ? times(minus(data["sphereCenter"], firstpoint), step) : true;
}
let expectedOuterDistance = distance(firstpoint, pt) * Math.sin(angleBetween(pt, firstpoint, secondpoint));
let distanceAlong = distance(firstpoint, pt) * Math.cos(angleBetween(pt, firstpoint, secondpoint))
if (expectedOuterDistance <= radius) {
return data["vec"] ? times(minus(data["sphereCenter"], plus(firstpoint, times(unit(minus(secondpoint, firstpoint)), distanceAlong))), step) : true;
}
return false;
}
//convert a sphere into a coplanar circle and check for collision
function sphereHitsPoly(sphereCenter, radius, poly, vec=false) {
let trueCentroid = center(poly);
let verticalDist = distInDir(poly.cross, trueCentroid, sphereCenter);
if (Math.abs(verticalDist) < radius) {
let crossSection = radius*Math.cos(Math.asin(Math.abs(verticalDist/radius)));
if (poly.some(pt => distance(trueCentroid, pt) >= distance(trueCentroid, sphereCenter)-crossSection)) {
return ptHitsTri(minus(sphereCenter, poly.cross.map(n => n*verticalDist)), crossSection, poly, {vec, sphereCenter, radius, poly});
}
}
return false;
}
//find the angle against the cross product of the poly, find the distance along the ray that it should collide (the intersection between the polygon's plane and the ray), and check if the intersection lies on the polygon
function rayHitsPoly(start, poly, vector, maxDistance=Infinity) {
vector = unit(vector);
let centroid = center(poly);
let dist = distInDir(poly.cross, centroid, start);
let normal = dist < 0 ? poly.cross : times(poly.cross, -1);
let angle = Math.acos(dotProduct(vector, normal));
if (angle >= Math.PI/2) {return false;}
let distance = Math.abs(dist)/Math.cos(angle);
if (distance > maxDistance) return false;
let potentialCollision = plus(start, times(vector, distance));
if (ptHitsTri(potentialCollision, 0, poly)) {
return {collision: potentialCollision, distance: distance};
}
return false;
}
//find if a line of sight is unblocked
function lineOfSight(start, shapes, end) {
let vec = minus(end, start);
let dist = distance(vec);
for (let shape of shapes) {
for (let poly of shape.rotatedPolys || shape.polys) {
let collision = rayHitsPoly(start, poly, vec, dist);
if (collision) return false;
}
}
return true;
}
//shoot a ray through a set of polygons and if it hits some, find the closest hit
function findRaycast(start, shapes, vector) {
let closest = null;
for (let shape of shapes) {
for (let poly of shape.rotatedPolys || shape.polys) {
let collision = rayHitsPoly(start, poly, vector);
if (collision && (closest === null || collision.distance < closest.distance)) {
closest = collision;
closest.poly = poly;
closest.shape = shape;
}
}
}
return closest;
}
let camFollow = null;
let points = [];
let shapes = [];
function circle(x, y, radius) {
ctx.arc(x, y, radius, 0, Math.PI*2);
ctx.fill();
ctx.closePath();
}
let camAngle = [0, 0], camPos = [0, 0, 0];
//convert a 3D coordinate into a 2D screen space coordinate, based on the FOV
function project(point) {
return [-point[0]/(point[2])*Math.tan(Math.PI/2-FOV[0]/2)/2*canvas.width+canvas.width/2, -point[1]/Math.abs(point[2])*Math.tan(Math.PI/2-FOV[1]/2)/2*canvas.height+canvas.height/2];
}
function clear(canvas) {
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.closePath();
}
//keep track of the last frame tick to monitor FPS
let lastTime = performance.now();
setInterval(function() {
if (gameState === "playing" && !isLoading) {
//if we were just playing and now we are not, we have just paused
if (keys["p"] || document.pointerLockElement === null || !document.hasFocus()) gameState = "justPaused";
}
if (gameState === "playing" && !isLoading) {
//dynamically maintain the resolution
canvas.width = window.innerWidth/canvasDivision;
canvas.height = window.innerHeight/canvasDivision;
let cameraSpeed = 1;
camFollow = player;
if (camFollow === null) {} else if (hp > 0) {
camPos[0] = camFollow.offset[0] + Math.sin(camAngle[0]) * cameraDistance * Math.cos(camAngle[1]);
camPos[1] = camFollow.offset[1] - Math.sin(camAngle[1]) * cameraDistance + cameraDistance/5 + .3;
camPos[2] = camFollow.offset[2] - Math.cos(camAngle[0]) * cameraDistance * Math.cos(camAngle[1]);
player.turn([camAngle[0]-player.rotate[0], 0, 0]);
//acceleration and movement from key inputs
let accelVec = [0, 0];
if (keys["w"]) accelVec = plus(accelVec, [-Math.sin(camAngle[0]), Math.cos(camAngle[0])]);
if (keys["s"]) accelVec = plus(accelVec, [Math.sin(camAngle[0]), -Math.cos(camAngle[0])]);
if (keys["a"]) accelVec = plus(accelVec, [Math.cos(camAngle[0]), Math.sin(camAngle[0])]);
if (keys["d"]) accelVec = plus(accelVec, [-Math.cos(camAngle[0]), -Math.sin(camAngle[0])]);
let horizVel = times(plus([playerVel[0], playerVel[2]], times(unit(accelVec), accelFactor*(keys["shift"]||aimFactor > 0 ? .3 : 1))), .5);
playerVel = [horizVel[0], playerVel[1], horizVel[1]];
let speed = distance([horizVel[0], Math.max(Math.abs(playerVel[1])-.2, 0), horizVel[1]]);
sway += speed;
//2x detailed physics - check horizontal movement first then vertical
let physicsSteps = 2;
for (let i = 0; i < physicsSteps; i++) {
player.move([playerVel[0]/physicsSteps, 0, playerVel[2]/physicsSteps]);
for (let poly of map.polys) {
let collides = sphereHitsPoly(player.offset, playerRadius, poly, true);
if (collides !== false) {
while (sphereHitsPoly(player.offset, playerRadius, poly)) {
player.move(collides);
playerVel = [playerVel[0]+collides[0], playerVel[1], playerVel[2]+collides[2]];
}
}
}
player.move([0, playerVel[1]/physicsSteps, 0]);
let hitGround = false;
if (playerVel[1] !== 0) {
for (let poly of map.polys) {
let collides = sphereHitsPoly(player.offset, playerRadius, poly)
if (collides !== false) {
if (playerVel[1] < 0) {
if (-playerVel[1] > 3) {
hp -= -playerVel[1]*4;
pain += .3;
}
hitGround = true;
}
while (sphereHitsPoly(player.offset, playerRadius, poly)) {
player.move([0, playerVel[1] <= 0 ? step : -step, 0]);
}
playerVel[1] = 0;
break;
}
}
}
if (hitGround && keys[" "]) {
playerVel[1] += jumpSpeed;
} else {
playerVel[1] -= gravity/physicsSteps;
}
if (keys["r"] && weaponTraits.get(gun).ammo !== weaponTraits.get(gun).totalAmmo && !reloading) {
reloading = true;
reloadTime = weaponTraits.get(gun).reloadPerShot ?
weaponTraits.get(gun).reloadTime * (weaponTraits.get(gun).totalAmmo-weaponTraits.get(gun).ammo) : weaponTraits.get(gun).reloadTime;
}
weaponTraits.forEach((traits, otherGun) => {
if (!reloading && keys[traits.slot.toString()] && otherGun !== gun) {
if (shapes.includes(gun)) shapes.splice(shapes.indexOf(gun), 1);
shapes.push(otherGun);
gun = otherGun;
shotCooldown = 10;
equipTimer = shotCooldown;
aimFactor = 0;
}
});
//manipulate bloom/spread level and position of viewmodel based on current movement and recoil
let idealBloom = Math.min(distance([playerVel[0], Math.max(0, Math.abs(playerVel[1])-gravity/2)*3, playerVel[2]])/5 * weaponTraits.get(gun).runningBloom + weaponTraits.get(gun).defaultBloom * (aimFactor === 1 ? 0.5 : 1), Math.PI/6);
bloom += (idealBloom-bloom)*.7 + recoil*Math.PI/150;
if (equipTimer === 0 && !reloading && (keys["q"] || rightMouseDown)) aimFactor = Math.min(aimFactor+1/6, 1);
else aimFactor = Math.max(aimFactor-0.2, 0);
gun.move(minus(weaponTraits.get(gun).normalPos.map((n, idx) => n+(weaponTraits.get(gun).aimPos[idx]-n)*aimFactor), gun.offset));
gun.move([0, 0, -recoil/3]);
gun.move([Math.sin(sway/5)*speed/7, Math.cos(sway/2.5)*-speed/10, 0])
gun.turn(minus([0, recoil/30, 0], gun.rotate));
gun.turn([(mouseMovement[0]*0.1+gun.rotate[0])*0.5, (-mouseMovement[1]*0.1+gun.rotate[1])*0.5, 0]);
gun.move([0, -equipTimer/1.5, 0]);
gun.turn([0, -equipTimer/20, 0]);
if (reloading) {
//reload animation (drop gun down then back up)
gun.move([0, 15*weaponTraits.get(gun).normalPos[1]*Math.sin(reloadTime/(weaponTraits.get(gun).reloadPerShot ?
weaponTraits.get(gun).reloadTime * (weaponTraits.get(gun).totalAmmo-weaponTraits.get(gun).ammo) : weaponTraits.get(gun).reloadTime)*Math.PI), 0]);
reloadTime -= 1;
if (reloadTime <= 0) {
weaponTraits.get(gun).ammo = weaponTraits.get(gun).totalAmmo;
reloading = false;
}
}
//if we are aiming, change the FOV and smoothly interpolate in between
FOV = FOV.map((n, idx) => trueFOV[idx]*(weaponTraits.get(gun).fovFactor === undefined ? (1-aimFactor/5) :
1-(1-weaponTraits.get(gun).fovFactor)*aimFactor));
recoil = Math.max((recoil-1)*.7, 0);
shotCooldown = Math.max(shotCooldown-1, 0);
equipTimer = Math.max(equipTimer-1, 0);
//spawn a shot - first, calculate the shot angle based on camera angle and spread. then check map for ray collisions
function spawnShot(startPos, angle, laserStartPos, damage, target) {
if (target === undefined) target = [map];
let shotVec = vecFromAngle(angle);
let hit = findRaycast(startPos, target, shotVec);
laserBeam(laserStartPos, hit ? hit.collision : plus(startPos, times(shotVec, 300)));
if (hit !== null) {
if (hit.shape === map) {
let bulletHole = copyShape(bulletHoleTemplate);
bulletHole.timer = 50;
bulletHoles.push(bulletHole);
bulletHole.move(minus(hit.collision, bulletHole.offset));
let cross = hit.poly.cross;
bulletHole.turn([Math.atan2(cross[2], cross[0])+Math.PI/2, Math.PI/2-Math.atan2(cross[1], Math.sqrt(cross[0]**2+cross[2]**2)), 0]);
bulletHole.move(times(cross, distInDir(cross, startPos, center(hit.poly)) < 0 ? .16 : -.16));
shapes.push(bulletHole);
} else if (enemies.includes(hit.shape)) {
if (damage !== undefined) {
if (hit.poly.mtl === "Head") damage *= 2;
hit.shape.health -= damage;
}
hitShot = (hit.shape.health === undefined || hit.shape.health) > 0 ? {state: 1, frames: 5} : {state: 2, frames: 10};
if (hit.poly.mtl === "Head") hitShot.headshot = true; else hitShot.headshot = false;
} else if (hit.shape === player) {
if (damage !== undefined) {hp -= damage; pain += .2;}
}
}
}
//when we click, spawn a shot and change camera angle as well as viewmodel
if (mouseDown && shotCooldown === 0 && weaponTraits.get(gun).ammo > 0 && !reloading) {
if (!weaponTraits.get(gun).automatic) mouseDown = false;
shotCooldown += weaponTraits.get(gun).cooldown;
recoil += weaponTraits.get(gun).recoil*(.75+Math.random()/2);
let shotAngle = deviate(camAngle, bloom);
let barrelTip = [gun.offset[0], -gun.offset[1], Math.max(...gun.polys.map(poly => Math.max(...poly.map(pt => pt[2]))))];
let barrelDist = 1;//distance(barrelTip);
let barrelAngle = [Math.atan2(barrelTip[2], barrelTip[0])-Math.PI/2, Math.atan2(barrelTip[2], barrelTip[1])-Math.PI/2];
let realGunPos = plus(camPos, times(vecFromAngle(camAngle.map((n, idx) => n+barrelAngle[idx])), barrelDist));
camAngle = [camAngle[0] + (Math.random()-.5)/100, Math.min(Math.PI/2, camAngle[1]+recoil/80*(aimFactor === 1 ? .7 : 1))];
weaponTraits.get(gun).ammo -= 1;
if (weaponTraits.get(gun).shots === undefined) spawnShot(camPos, shotAngle, realGunPos, weaponTraits.get(gun).damage, [map, ...enemies]);
else {
for (let i = 0; i < weaponTraits.get(gun).shots; i++) {
let newShot = deviate(shotAngle, weaponTraits.get(gun).spread);
spawnShot(camPos, newShot, realGunPos, weaponTraits.get(gun).damage, [map, ...enemies]);
}
}
}
}
}
//update enemy list, bullet hole list, and bullet tracer list
if (gameActive) {
for (let i = 0; i < enemies.length; i++) {
let enemy = enemies[i];
if (enemy.health <= 0) {
enemies.splice(i, 1);
if (shapes.includes(enemy)) shapes.splice(shapes.indexOf(enemy), 1);
i--;
continue;
}
let angle = (Math.atan2(camPos[2]-enemy.offset[2], camPos[0]-enemy.offset[0])-Math.PI/2) - enemy.rotate[0];
angle = Math.min(Math.abs(angle), Math.abs(Math.PI*2-angle)) === Math.abs(angle) ? angle : angle-Math.PI*2;
enemy.turn([angle * .1, 0, 0]);
if (Math.random() < enemyShotChance && lineOfSight(enemy.offset, [map], camPos)) {
spawnShot(enemy.offset, deviate([enemy.rotate[0], -Math.atan2(distance([camPos[0], camPos[2]], [enemy.offset[0], enemy.offset[2]]), camPos[1]-enemy.offset[1])+Math.PI/2, enemy.rotate[1]], enemyBloom), enemy.offset, enemyDamage, [map, player]);
}
}
}
for (let i = 0; i < bulletHoles.length; i++) {
let bulletHole = bulletHoles[i];
if (bulletHole.timer <= 0) {
bulletHoles.splice(i, 1);
if (shapes.includes(bulletHole)) shapes.splice(shapes.indexOf(bulletHole), 1);
i -= 1;
}
bulletHole.timer -= 1;
}
for (let i = 0; i < laserBeams.length; i++) {
let laserBeam = laserBeams[i];
if (laserBeam.timer <= 0) {
laserBeams.splice(i, 1);
if (shapes.includes(laserBeam)) shapes.splice(shapes.indexOf(laserBeam), 1);
i -= 1;
}
laserBeam.timer -= 1;
}
//camera rotation matrices - see https://en.wikipedia.org/wiki/Rotation_matrix
let yaw = matrix.from([[Math.cos(camAngle[0]), -Math.sin(camAngle[0]), 0], [Math.sin(camAngle[0]), Math.cos(camAngle[0]), 0], [0, 0, 1]]);
let roll = matrix.from([[1, 0, 0], [0, Math.cos(camAngle[1]), -Math.sin(camAngle[1])], [0, Math.sin(camAngle[1]), Math.cos(camAngle[1])]]);
let pitch = matrix.from([[Math.cos(camAngle[0]), 0, Math.sin(camAngle[0])], [0, 1, 0], [-Math.sin(camAngle[0]), 0, Math.cos(camAngle[0])]]);
let transformCamera = roll.multiply(pitch);
points = []
//convert each shape into a list of transformed polygons
let renderList = [];
for (let shape of shapes) {
let transformCache = new Map();
for (let poly of (shape.rotatedPolys === null ? shape.polys : shape.rotatedPolys)) {
let pts = poly.map(pt => [[pt[0]], [pt[1]], [pt[2]]]);
let cross = poly.cross; if (shape.viewmodel) cross = unit(plus(times(vecFromAngle(camAngle), .4), cross));
let dot = dotProduct(cross, unit([.5, -1, .5]));
let cameraDot = dotProduct(cross, unit([pts[1][0]-camPos[0], pts[1][1]-camPos[1], pts[1][2]-camPos[2]]));
if (!shape.viewmodel) {
pts = pts.map(pt => {
let str = JSON.stringify(pt);
if (transformCache.has(str)) {
return transformCache.get(str)
} else {
let transformed = transformCamera.multiply(matrix.from([[pt[0]-camPos[0]], [pt[1]-camPos[1]], [pt[2]-camPos[2]]])).list;
transformCache.set(str, transformed);
return transformed;
}
});
}
//clip polygons that pass partially behind the camera
if (pts.some(pt => pt[2] < 0)) {
pts = pts.map(pt => pt.map(arr=>arr[0]))
let usable = pts.filter(pt => pt[2] > 0);
if (usable.length >= 1) {
let threshold = .08;
let idx = pts.indexOf(usable[0]);
let newPts = [];
while (pts[idx%pts.length][2] > 0) {
newPts.push(pts[idx%pts.length]);
idx++;
}
let [last, curr] = [pts[(idx-1)%pts.length].map(Number), pts[idx%pts.length].map(Number)]
let ratio = (threshold-curr[2])/(last[2]-curr[2]);
let newPt = [curr[0]+ratio*(last[0]-curr[0]),curr[1]+ratio*(last[1]-curr[1]),threshold];
while (pts[idx%pts.length][2] <= 0) idx++;
if (!newPts.includes(pts[idx%pts.length])) lastPt = pts[idx%pts.length];
[last, curr] = [pts[(idx-1)%pts.length].map(Number), pts[idx%pts.length].map(Number)];
ratio = (threshold-curr[2])/(last[2]-curr[2]);
newPts.push(newPt);
newPts.push([curr[0]+ratio*(last[0]-curr[0]),curr[1]+ratio*(last[1]-curr[1]),threshold]);
while (pts[idx%(pts.length)] != newPts[0]) {
newPts.push(pts[idx%(pts.length)])
idx++;
}
pts = newPts.map(pt => pt.map(n => [n]));
} else continue;
}
let centroid = center(pts);
if (!shape.viewmodel && cameraDot > 0) dot = -dot;
let rgb = null;
if (poly.mtl in materials) rgb = materials[poly.mtl];
else rgb = [128, 128, 128];
rgb = rgb.map(n => n*(1-dot/2.5));
pts.mtl = rgb;
pts.meanZ = Math.sqrt((centroid[0])**2+(centroid[1])**2+(centroid[2])**2);
pts.viewmodel = shape.viewmodel === true;
renderList.push(pts);
}
}
//render each polygon
renderList.sort((a, b) => b.meanZ-a.meanZ);
var canvasData = ctx.createImageData(canvas.width, canvas.height);
let depthBuffer = Object.create(null);
let viewmodelBuffer = Object.create(null);
for (let pts of renderList) {
drawPoly(pts.map(pt => {let newPt = project(pt); newPt.depth = 1/pt[2][0]; return newPt;}), canvasData, depthBuffer, pts.mtl, viewmodelBuffer, pts.viewmodel);
}
//draw sky (solid color)
for (let i = 0; i < canvasData.height; i++) {
for (let j = 0; j < canvasData.width; j++) {
let index = (j + i * canvas.width) * 4;
if (depthBuffer[index] === undefined) {
canvasData.data[index] = 135;
canvasData.data[index+1] = 206;
canvasData.data[index+2] = 235;
canvasData.data[index+3] = 255;
}
}
}
ctx.putImageData(canvasData, 0, 0);
//UI elements including crosshair, ammo, and health
let difference = performance.now()-lastTime;
lastTime = performance.now();
let fps = 1000/difference;
if (showFPS) drawText(ctx, "FPS: " + Math.round(fps), canvas.width-114/canvasDivision, canvas.height-24/canvasDivision, 30/canvasDivision, "black", "left");
ctx.fillStyle = "rgba(0, 0, 0, .5)";
ctx.strokeStyle = `rgba(0, 0, 0, ${1-aimFactor/1})`;
let totalBloom = Math.max(bloom + (weaponTraits.get(gun).spread || 0), Math.PI/500);
let bloomX = project([-Math.cos(Math.PI/2-totalBloom/2), 0, Math.sin(Math.PI/2-totalBloom/2)])[0]-canvas.width/2,
bloomY = project([0, -Math.cos(Math.PI/2-totalBloom/2), Math.sin(Math.PI/2-totalBloom/2)])[1]-canvas.height/2;
if (gameActive && showCrosshair) ctx.ellipse(canvas.width/2, canvas.height/2, bloomX, bloomY, 0, 0, Math.PI*2);
ctx.stroke();
let hpColor = `rgb(${Math.min((100-hp)*255/50, 255)}, ${Math.min(hp*255/50, 255)}, 0)`;
ctx.beginPath();
ctx.fillStyle = "black";
if (showHP) {
ctx.strokeWidth = 5;
ctx.roundRect(canvas.width-143/canvasDivision, 17/canvasDivision, 126/canvasDivision, 26/canvasDivision, 13/canvasDivision);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = hpColor;
ctx.roundRect(canvas.width-140/canvasDivision, 20/canvasDivision, Math.max(120*hp/100/canvasDivision, 2), 20/canvasDivision, 10/canvasDivision);
ctx.fill();
}
if (showAmmo) {
ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.beginPath();
ctx.roundRect(0, canvas.height-250/canvasDivision, 300/canvasDivision, 170/canvasDivision, 5);
ctx.fill();
ctx.textAlign = "center";
drawText(ctx, weaponTraits.get(gun).name, 150/canvasDivision, canvas.height-200/canvasDivision, 50/canvasDivision, "white");
drawText(ctx, reloading ? "Reloading" : `${weaponTraits.get(gun).ammo}/${weaponTraits.get(gun).totalAmmo}`, 150/canvasDivision, canvas.height-130/canvasDivision, 50/canvasDivision, (reloading || weaponTraits.get(gun).ammo === 0) ? "red" : "white");
}
if (hitShot.frames > 0 && showHits) {
if (hitShot.state === 1) ctx.drawImage(hitMarker, canvas.width/2+100/canvasDivision, canvas.height/2-50/canvasDivision, 100/canvasDivision, 100/canvasDivision);
else ctx.drawImage(skullIcon, canvas.width/2+100/canvasDivision, canvas.height/2-50/canvasDivision, 100/canvasDivision, 100/canvasDivision);
if (hitShot.headshot) ctx.drawImage(headshot, canvas.width/2+225/canvasDivision, canvas.height/2-50/canvasDivision, 100/canvasDivision, 100/canvasDivision);
} else hitShot.headshot = false;
hitShot.frames -= 1;
pain = gameActive ? Math.min(pain, .4) : pain;
ctx.fillStyle = pain >= 0 ? `rgba(255, 0, 0, ${pain})` : `rgba(0, 255, 0, ${-pain})`;
ctx.fillRect(0, 0, canvas.width, canvas.height);
pain = gameActive ? Math.max(pain-0.05, 0) : pain;
//check for game over
if (gameActive) {
if (hp <= 0) {
gameActive = false; resume.visible = false;
pain = .4;
shapes.splice(shapes.indexOf(gun), 1);
}
if (enemies.length === 0) {
gameActive = false; resume.visible = false;
pain = 0;
}
} else {
if (hp <= 0) {
pain += 0.01;
accelFactor = 0;
ctx.globalAlpha = Math.min(pain, .8);
drawText(ctx, "You Died!", canvas.width/2, 50/canvasDivision, 50/canvasDivision, "black", "center", "Georgia");
ctx.globalAlpha = 1;
if (pain >= 1) {gameState = "menu"; document.exitPointerLock();}
}
if (enemies.length <= 0) {
pain -= 0.02;
ctx.globalAlpha = -Math.max(pain, -.8);
drawText(ctx, "You Win!", canvas.width/2, 50/canvasDivision, 50/canvasDivision, "black", "center", "Georgia");
accelFactor *= .95;
ctx.globalAlpha = 1;
if (pain <= -1) {gameState = "menu"; document.exitPointerLock();}
}
}
//maintain a specific framerate by changing resolution
if (fps < frameBounds[0]) canvasDivision += 0.25;
if (fps > frameBounds[1]) canvasDivision -= 0.25;
}
canvas.style.cursor = "auto";
if (gameState === "paused") {
//if mouse down while paused, resume
if (mouseDown) {
(async function() {
await canvas.requestPointerLock();
if (document.pointerLockElement === canvas) {
gameState = "playing";
mouseDown = false;
}
})();
}
}
if (gameState === "justPaused") {
//pause screen
document.exitPointerLock();
gameState = "paused";
ctx.fillStyle = "rgba(175, 175, 175, 0.8)";
ctx.beginPath();
ctx.roundRect(canvas.width/2-300/canvasDivision, canvas.height/2-200/canvasDivision, 600/canvasDivision, 215/canvasDivision, 5);
ctx.fill();
drawText(ctx, "Paused!", canvas.width/2, canvas.height/2-140/canvasDivision, 60/canvasDivision, "black", "center", "Helvetica");
drawText(ctx, "Click anywhere to resume", canvas.width/2, canvas.height/2-80/canvasDivision, 40/canvasDivision, "black", "center", "Helvetica");
drawText(ctx, "Press 'm' to return to the menu", canvas.width/2, canvas.height/2-30/canvasDivision, 40/canvasDivision, "black", "center", "Helvetica");
}
if ((gameState === "playing" || gameState === "paused") && keys["m"]) {
//return to menu if m is pressed
gameState = "menu";
document.exitPointerLock();
}
if (gameState === "menu" || gameState === "credits" || gameState === "instructions") {
//draw and handle buttons
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
clear(canvas);
ctx.fillStyle = "lightblue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (gameState === "menu") {
let [width, height] = [getComputedStyle(canvas).width.replace("px", ""), getComputedStyle(canvas).height.replace("px", "")].map(Number);
ctx.drawImage(thumbnail, width/2-(width+50)/2-(mouseX-50)/2, height/2 - (height+50)/2-(mouseY-50)/2, width+50, height+50);
ctx.drawImage(logo, canvas.width/2-logo.width*.65, 30, logo.width, logo.height);
}
let hitButton = false;
for (let button of Button.buttons) {
if (button.visible && button.props.targetScreen === gameState) {
button.draw();
if (mouseDown && button.isHovering(mouseX, mouseY)) {
button.props.event();
hitButton = true;
}
}
}
if (!hitButton) mouseDown = false;
}
if (gameState === "credits") {
drawText(ctx, "Credits", canvas.width/2, 30, 40, "black", "center", "Helvetica");
drawText(ctx, "Valley Terrain by Zsky [CC-BY] (https://creativecommons.org/licenses/by/3.0/)", canvas.width/2, 70, 20, "black", "center", "Trebuchet MS");
drawText(ctx, "via Poly Pizza (https://poly.pizza/m/u78ByZHYB2); modified", canvas.width/2, 92, 20, "black", "center", "Trebuchet MS");
}
if (gameState === "instructions") {
drawText(ctx, "Instructions", canvas.width/2, 30, 40, "black", "center", "Helvetica");
drawText(ctx, "WASD/space to move, mouse to shoot, keys 1-4 to select gun, q/RMB to aim, shift to walk, and r to reload", canvas.width/2, 70, 20, "black", "center", "Trebuchet MS");
}
}, 30);
//object lists and spawn functions for bullet holes, tracers, and enemies
let bulletHoles = [];
let enemies = [];
function spawnEnemy(pos) {
let enemy = copyShape(enemyTemplate);
enemy.move(minus(pos, enemy.offset));
let enemyHeight = Math.min(...map.polys.map(poly => Math.min(...poly.map(pt => pt[1]))));
enemy.move([0, -enemyHeight/2, 0]);
enemy.health = 100;
enemies.push(enemy);
shapes.push(enemy);
}
let bullets = [];
function spawnShot(from, target=false) {
let shot = copyShape(bullet);
shot.update(from.rotate[0], "yaw");
shot.update(-from.rotate[1], "pitch");
shot.move(from.offset.map((n, idx) => n-shot.offset[idx]));
shot.moveInDirection(2+Math.random()-.5);
shot.distance = 0;
shapes.push(shot);
bullets.push(shot);
if (target && enemy !== null) {
let lead = leadAim(player.offset, enemy.offset, bulletVel, [enemy.localFrame.roll[1], enemy.localFrame.roll[2], enemy.localFrame.roll[0]].map(n=>n*enemyVel));
let currentAim = [player.localFrame.roll[1], player.localFrame.roll[2], player.localFrame.roll[0]];
if (Math.acos(dotProduct(unit(lead[1].map((n, idx) => n-player.offset[idx])), currentAim)) < aimAssistRange) {
shot.localFrame.roll = [lead[0][2], lead[0][0], lead[0][1]];
}
}
shot.localFrame.roll = unit(shot.localFrame.roll.map(n => n+(Math.random()-0.5)*0.05));
}
let laserBeams = [];
function laserBeam(pos1, pos2) {
let width = .03;
let laser = new Shape([[[pos1[0], pos1[1]+width, pos1[2]], [pos1[0], pos1[1]-width, pos1[2]], [pos2[0], pos2[1]-width, pos2[2]], [pos2[0], pos2[1]+width, pos2[2]]]]);
for (let poly of laser.polys) {
poly.mtl = "Bullet";
}
laser.updateCrossProducts();
laser.timer = 1;
laserBeams.push(laser);
shapes.push(laser);
}
canvas.addEventListener("mousemove", function(e) {
if (gameState === "playing") {
let factor = FOV[0] / trueFOV[0];
camAngle[0] += e.movementX/200 * factor;
camAngle[1] = Math.max(Math.min(camAngle[1]-e.movementY/200*factor, Math.PI/2), -Math.PI/2);
mouseMovement = [e.movementX/200, e.movementY/200];
} else {
let bd = canvas.getBoundingClientRect();
let mousePos = [(e.clientX - bd.left)*canvas.width/Number(getComputedStyle(canvas).width.replace("px", "")), (e.clientY - bd.top)*canvas.height/Number(getComputedStyle(canvas).height.replace("px", ""))];
mouseX = mousePos[0]/canvas.width*100; mouseY = mousePos[1]/canvas.height*100;
}
});
canvas.addEventListener("mousedown", function(e) {
if (e.button !== 0) {
e.preventDefault(); e.stopPropagation();
if (e.button === 2) {
rightMouseDown = true;
}return;
}
mouseDown = true;
});
canvas.addEventListener("contextmenu", e => e.preventDefault());