-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
810 lines (682 loc) · 33.6 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<title>Flappy2.0</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<style>
canvas {
display: block;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<canvas id="static" style="z-index: 0;"></canvas>
<canvas id="dynamic" style="z-index: 1;"></canvas>
<canvas id="ui" style="z-index: 2;"></canvas>
<canvas id="effects" style="z-index: 3;"></canvas>
<div id="PlayButton"></div>
<script>
///////////////////////
/// GLOBAL SETTINGS ///
///////////////////////
// Used for debugging
const SHOW_COLLISION_SHAPES = false;
// Fixed step used for physics update
const FIXED_DELTA_TIME = 1.0/60.0;
// Limit rendering
const RENDER_LIMIT = 1.0/60.0;
// Delays the game over screen, when the player dies to the ground
const PLAYER_DEAD_FROM_GROUND_DELAY = 0.5
//////////////////////
/// PLANE SETTINGS ///
//////////////////////
// Gravity applied to the player
const GRAVITY = 500;
// The radius used for collision detection
const PLANE_CIRCLE_COLLISION_RADIUS = 40;
// The velocity change on touch/mouse press
const PLANE_JUMP_VELOCITY = 300;
// The speed at which the world scrolls
const PLANE_SPEED = 150;
// As the plane sprite is pretty big by itself
const PLANE_SCALE = 0.55;
// Additional offset from the middle to give player more view
const PLANE_OFFSET = 50;
// Defines the duration of the whole animation
const PLANE_ANIMATION_SPEED = 0.2;
//////////////////////
/// SPIKE SETTINGS ///
//////////////////////
// CanvasWidth is normal distance, this is applied to it
const SPIKE_DISTANCE_FACTOR = 0.75;
// How much the spikes can vary in gap
const SPIKE_GAP_RANGE = [150, 250];
// How much the spikes can vary in height
const SPIKE_HEIGHT_RANGE = [-70, 100];
////////////////////////
/// EFFECTS SETTINGS ///
////////////////////////
// The length of the effect
const SCREEN_FLASH_DURATION = 0.25;
// The refresh rate of the effect
const SCREEN_FLASH_REFRESH_RATE = 1.0 / 30.0;
//////////////////////
/// SCORE SETTINGS ///
//////////////////////
// The scale applied to the score
const SCORE_SCALE = 0.5;
////////////////////////
/// GLOBAL VARIABLES ///
////////////////////////
// Used to render moving images (redrawn)
var gDynamicContext;
// Used to render static images
var gStaticContext;
// Used for displaying the HUD and menus
var gUIContext;
// Used for displaying effects
var gUIContext;
// The sprite sheet
var gSheet;
// Aka window width (inner)
var gCanvasWidth;
// Aka window height (inner)
var gCanvasHeight;
// Used to scale all images (height defines width)
var gCanvasAspectRatio;
// The ground sprite
var gGround;
// The x position of the currently visible ground
var gGroundPosX = 0;
// The x position of the "next" ground
var gNextGroundPosX = 0;
// The plane of the player
var gPlane;
// Play button
var gButtonPlay;
var gButtonLarge;
var gLetterP;
var gLetterL;
var gLetterA;
var gLetterY;
// Spikes
var gSpikeUp;
var gSpikeDown;
// Left, middle and right spikes
var gSpikes = [];
var gSpikeDistance = 0;
// Score
var gScore = 0;
var gDigits = [];
var gScoreUpdated = false;
const GameState = {
NONE: 0,
START_MENU: 1,
PLAYING: 2,
GAME_OVER: 3
}
var gGameState = GameState.START_MENU;
var gPrevGameState = GameState.NONE;
// Wait for window to load before starting
window.onload = function() {
main();
}
function main(){
// Get window size
gCanvasWidth = window.innerWidth;
gCanvasHeight = window.innerHeight;
// Setup static canvas for background
var staticCanvas = document.getElementById("static");
staticCanvas.width = gCanvasWidth;
staticCanvas.height = window.innerHeight;
gStaticContext = staticCanvas.getContext("2d");
// Setup dynamic canvas for moving objects
var dynamicCanvas = document.getElementById("dynamic");
dynamicCanvas.width = gCanvasWidth;
dynamicCanvas.height = gCanvasHeight;
gDynamicContext = dynamicCanvas.getContext("2d");
// Setup UI canvas for displaying HUD and menus
var uiCanvas = document.getElementById("ui");
uiCanvas.width = gCanvasWidth;
uiCanvas.height = gCanvasHeight;
gUIContext = uiCanvas.getContext("2d");
// Setup UI canvas for displaying HUD and menus
var effectsCanvas = document.getElementById("effects");
effectsCanvas.width = gCanvasWidth;
effectsCanvas.height = gCanvasHeight;
gEffectsContext = effectsCanvas.getContext("2d");
// Mouse events
window.onmousedown = function(mouse){
onMouseClick(mouse);
}
// Load sprite sheet
sheet = new Image();
sheet.onload = function(){
runGame();
}
sheet.src = "sheet.png";
}
function getTimestamp(){
// If performance is supported, use it
return window.performance ? window.performance.now() : Date.now();
}
function runGame(){
// As the background sprite has to cover everything, it defines the aspect ratio
var backgroundHeight = 480;
gCanvasAspectRatio = gCanvasHeight / backgroundHeight;
// Add static background
var backgroundSprite = new Sprite(sheet, 0, 355, 800, 480, gCanvasAspectRatio);
backgroundSprite.draw(gStaticContext, 0, 0);
// Ground that will be moving to simulate movement
gGround = new Sprite(sheet, 0, 0, 807, 71, gCanvasAspectRatio);
// Move the second ground to start position
gNextGroundPosX = gGround.width * gCanvasAspectRatio;
// Get animation frames for plane
var plane_frame1 = new Sprite(sheet, 330, 1371, 88, 72.5, gCanvasAspectRatio);
var plane_frame2 = new Sprite(sheet, 372, 1132, 88, 72.5, gCanvasAspectRatio);
var plane_frame3 = new Sprite(sheet, 222, 1562, 88, 72.5, gCanvasAspectRatio);
gPlane = new Plane(plane_frame1, plane_frame2, plane_frame3, PLANE_ANIMATION_SPEED);
// Play button sprites
gButtonLarge = new Sprite(sheet, 0, 1250, 196, 70, gCanvasAspectRatio);
gLetterP = new Sprite(sheet, 489, 1427, 48, 65, gCanvasAspectRatio);
gLetterL = new Sprite(sheet, 512, 899, 44, 64, gCanvasAspectRatio);
gLetterA = new Sprite(sheet, 412, 835, 61, 64, gCanvasAspectRatio);
gLetterY = new Sprite(sheet, 432, 1473, 57, 64, gCanvasAspectRatio);
// Spikes
gSpikeUp = new Sprite(sheet, 0, 1757, 108, 239, gCanvasAspectRatio);
gSpikeDown = new Sprite(sheet, 265, 986, 106, 238, gCanvasAspectRatio);
gSpikeDistance = gCanvasWidth * SPIKE_DISTANCE_FACTOR;
setupSpikes();
// Setup numbers
let gDigit0 = new Sprite(sheet, 432, 1743, 53, 77, gCanvasAspectRatio);
let gDigit1 = new Sprite(sheet, 513, 1093, 37, 76, gCanvasAspectRatio);
let gDigit2 = new Sprite(sheet, 477, 1350, 51, 77, gCanvasAspectRatio);
let gDigit3 = new Sprite(sheet, 486, 1679, 51, 77, gCanvasAspectRatio);
let gDigit4 = new Sprite(sheet, 432, 1537, 55, 75, gCanvasAspectRatio);
let gDigit5 = new Sprite(sheet, 486, 1823, 50, 75, gCanvasAspectRatio);
let gDigit6 = new Sprite(sheet, 432, 1885, 53, 77, gCanvasAspectRatio);
let gDigit7 = new Sprite(sheet, 479, 1173, 51, 75, gCanvasAspectRatio);
let gDigit8 = new Sprite(sheet, 461, 899, 51, 77, gCanvasAspectRatio);
let gDigit9 = new Sprite(sheet, 459, 1962, 51, 77, gCanvasAspectRatio);
gDigits.push(gDigit0);
gDigits.push(gDigit1);
gDigits.push(gDigit2);
gDigits.push(gDigit3);
gDigits.push(gDigit4);
gDigits.push(gDigit5);
gDigits.push(gDigit6);
gDigits.push(gDigit7);
gDigits.push(gDigit8);
gDigits.push(gDigit9);
var last = getTimestamp();
let deltaAccumulator = 0;
let renderAccumulator = 0;
// Main loop
var loop = function(){
updateGameState();
var now = getTimestamp();
var delta = (now - last) / 1000.0;
last = now;
deltaAccumulator += delta;
while(deltaAccumulator >= FIXED_DELTA_TIME){
update(FIXED_DELTA_TIME);
deltaAccumulator -= FIXED_DELTA_TIME;
}
renderAccumulator += delta;
if(renderAccumulator >= RENDER_LIMIT){
render(delta);
renderAccumulator -= RENDER_LIMIT;
}
window.requestAnimationFrame(loop)
}
window.requestAnimationFrame(loop)
}
function updateGameState() {
// Start of game
if(gGameState == GameState.START_MENU && gPrevGameState != GameState.START_MENU){
addPlayButton();
gPrevGameState = gGameState;
}
// Player died
if(gGameState == GameState.GAME_OVER && gPrevGameState == GameState.PLAYING){
addPlayButton();
gPrevGameState = gGameState;
}
// Player pressed start
if(gGameState == GameState.PLAYING && gPrevGameState != GameState.PLAYING){
resetGame();
clearUICanvas();
updateScoreUI();
gPrevGameState = gGameState;
}
}
function update(delta){
// Pause everything in GameOver screen
if(gGameState == GameState.GAME_OVER){
return;
}
// Only move world if player isn't dead
if(!gPlane.isDying){
// Move along x
gPlane.worldPosX += PLANE_SPEED * delta;
}
// If the current ground is out of view, update positions
if(gPlane.worldPosX > gNextGroundPosX){
gGroundPosX = gNextGroundPosX;
gNextGroundPosX = gNextGroundPosX + gGround.width * gCanvasAspectRatio;
}
// Nothing to do if player isn't playing
if(gGameState != GameState.PLAYING){
return;
}
// Update player physics
gPlane.update(delta);
// Nothing to do if player died
if(gPlane.isDying){
return;
}
// If player reached middle spike, move left to right
if(gPlane.worldPosX > gSpikes[1].x){
var newRightSpike = gSpikes[0];
gSpikes[0] = gSpikes[1];
gSpikes[1] = gSpikes[2];
// Give it new height and gap
newRightSpike.setRandomGapAndHeight(SPIKE_GAP_RANGE, SPIKE_HEIGHT_RANGE);
newRightSpike.x = gSpikes[2].x + gSpikeDistance;
gSpikes[2] = newRightSpike;
gScoreUpdated = false;
}
if(gPlane.worldPosX > gSpikes[1].x - gPlane.posX + gPlane.plane_frames[0].width * PLANE_SCALE * gCanvasAspectRatio && !gScoreUpdated){
gScoreUpdated = true;
gScore++;
updateScoreUI();
}
// Check if plane collides with any spikes
let planeX = gPlane.posX + gPlane.plane_frames[0].width / 2 * PLANE_SCALE * gCanvasAspectRatio;
let planeY = gPlane.posY + gPlane.plane_frames[0].height / 2 * PLANE_SCALE * gCanvasAspectRatio;
// Only necessary to check middle spikes
if(gSpikes[1].isCollidingWithCircle(planeX, planeY, PLANE_CIRCLE_COLLISION_RADIUS, gPlane.worldPosX)){
gPlane.die();
}
}
function render(delta){
// Remove everything from dynamic canvas
gDynamicContext.clearRect(0,0, gCanvasWidth, gCanvasHeight);
// Hide spikes in the start screen (scrolling of the world would otherwise reveal them)
if(gGameState != GameState.START_MENU){
renderSpikes(gDynamicContext);
}
renderGrounds(gDynamicContext);
renderPlane(gDynamicContext, delta);
}
function renderGrounds(context){
// Draw current ground
gGround.draw(context, gGroundPosX - gPlane.worldPosX, gCanvasHeight - gGround.height * gCanvasAspectRatio);
// Draw ground out of view
gGround.draw(context, gNextGroundPosX - gPlane.worldPosX, gCanvasHeight - gGround.height * gCanvasAspectRatio);
}
function renderPlane(context, delta){
gPlane.draw(context, PLANE_SCALE, delta);
}
function renderSpikes(context) {
gSpikes.forEach(spike => {
spike.draw(context, gPlane.worldPosX);
});
}
// Resets all necessary variables
function resetGame() {
// Re-setup spikes resets them
setupSpikes();
gGroundPosX = 0;
gNextGroundPosX = gGround.width * gCanvasAspectRatio;
gPlane.reset();
gScore = 0;
}
// Creates three spikes: Left, middle, right
// The player is only able to see two at the same time -> used to move spikes unnoticed
function setupSpikes() {
gSpikes.length = 0;
let spike = new Spike(gSpikeUp, gSpikeDown, -gCanvasWidth);
spike.setRandomGapAndHeight(SPIKE_GAP_RANGE, SPIKE_HEIGHT_RANGE);
gSpikes.push(spike);
spike = new Spike(gSpikeUp, gSpikeDown, gCanvasWidth);
spike.setRandomGapAndHeight(SPIKE_GAP_RANGE, SPIKE_HEIGHT_RANGE);
gSpikes.push(spike);
spike = new Spike(gSpikeUp, gSpikeDown, gCanvasWidth + gSpikeDistance);
spike.setRandomGapAndHeight(SPIKE_GAP_RANGE, SPIKE_HEIGHT_RANGE);
gSpikes.push(spike);
}
// Clears the UI
function clearUICanvas(){
gUIContext.clearRect(0,0, gCanvasWidth, gCanvasHeight);
}
// Adds the play button to the UICanvas
function addPlayButton(){
var buttonScale = 0.5;
var buttonX = gCanvasWidth / 2 - (gButtonLarge.width / 2 * buttonScale * gCanvasAspectRatio);
var buttonY = gCanvasHeight / 2;
var buttonWidth = gButtonLarge.width * gCanvasAspectRatio * buttonScale;
var buttonHeight = gButtonLarge.height * gCanvasAspectRatio * buttonScale;
gButtonPlay = new Button(buttonX, buttonY, buttonWidth, buttonHeight)
// Draw all necessary sprites
gButtonLarge.draw(
gUIContext,
buttonX,
buttonY,
buttonScale
);
gLetterP.draw(
gUIContext,
gCanvasWidth / 2 - (gButtonLarge.width / 2 * buttonScale * 0.95 * gCanvasAspectRatio),
gCanvasHeight / 2,
buttonScale
);
gLetterL.draw(
gUIContext,
gCanvasWidth / 2 - (gButtonLarge.width / 2 * buttonScale * 0.5 * gCanvasAspectRatio),
gCanvasHeight / 2,
buttonScale
);
gLetterA.draw(
gUIContext,
gCanvasWidth / 2 - (gButtonLarge.width / 2 * buttonScale * 0.05 * gCanvasAspectRatio),
gCanvasHeight / 2,
buttonScale
);
gLetterY.draw(
gUIContext,
gCanvasWidth / 2 + (gButtonLarge.width / 2 * buttonScale * 0.4 * gCanvasAspectRatio),
gCanvasHeight / 2,
buttonScale
);
}
function updateScoreUI(){
// Clear old score
clearUICanvas();
// Get the amount of digits required to display the score
let digitCount = (Math.log10(gScore) | 0) + 1;
let width = gDigits[0].width * SCORE_SCALE * gCanvasAspectRatio;
let currentScore = gScore;
for(let i = 0; i < digitCount; i++){
// Get digit number
let currentDigit = currentScore % 10;
// Move to next digit
currentScore = (currentScore / 10) | 0;
let offset = width * (i - digitCount / 2);
// Draw with offset
gDigits[currentDigit].draw(gUIContext, gCanvasWidth / 2 - offset - width, gCanvasHeight * 0.05, SCORE_SCALE)
}
}
// All on-click events
function onMouseClick(mouse){
// Jump event
if(gGameState == GameState.PLAYING){
gPlane.jump();
}
// Play butten pressed event
if(gGameState == GameState.START_MENU || gGameState == GameState.GAME_OVER){
if(gButtonPlay.isInside(mouse.clientX, mouse.clientY)){
gGameState = GameState.PLAYING;
}
}
}
// Shows the screen flash animation with a specified duration and refresh rate (in seconds)
function showScreenFlash(duration, refreshRate) {
var step = 1.0 / (duration / refreshRate);
gEffectsContext.fillStyle = "#FFFFFF";
gEffectsContext.fillRect(0, 0, gCanvasWidth, gCanvasHeight)
var currentAlpha = 1.0;
function screenFlashAnimation() {
gEffectsContext.clearRect(0, 0, gCanvasWidth, gCanvasHeight);
currentAlpha -= step;
gEffectsContext.globalAlpha = currentAlpha;
gEffectsContext.fillStyle = "#FFFFFF";
gEffectsContext.fillRect(0, 0, gCanvasWidth, gCanvasHeight)
if(currentAlpha <= 0){
clearInterval(screenFlashInterval);
}
}
var screenFlashInterval = setInterval(screenFlashAnimation, refreshRate * 1000);
}
// A sprite consists of an image, size and position
class Sprite{
constructor(image, x, y, width, height, aspectRatio){
this.image = image;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.aspectRatio = aspectRatio
}
// Draws the image at the specified pixel position
draw(context, x, y, scale = 1){
context.drawImage(
this.image,
this.x,
this.y,
this.width,
this.height,
x,
y,
this.width * this.aspectRatio * scale,
this.height * this.aspectRatio * scale)
}
}
class Button{
constructor(x, y, width, height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
// Whether the provided mouse position is inside this button
isInside(mouseX, mouseY){
return mouseX >= this.x && mouseX <= this.x + this.width &&
mouseY >= this.y && mouseY <= this.y + this.height;
}
}
class Spike{
constructor(spikeUp, spikeDown, x){
this.spikeUp = spikeUp;
this.spikeDown = spikeDown;
this.x = x;
this.gap = 0;
this.height_offset = 0;
}
draw(context, worldPos){
// Draw upper spike
this.spikeDown.draw(
context,
this.x - worldPos,
-this.gap / 2 - this.height_offset
);
// Draw lower spike
this.spikeUp.draw(
context,
this.x - worldPos,
gCanvasHeight - this.spikeUp.height * gCanvasAspectRatio + this.gap / 2 - this.height_offset
);
// Render spike tip collision point and spike collision edge
if(SHOW_COLLISION_SHAPES){
let planeX = gPlane.posX + gPlane.plane_frames[0].width / 2 * PLANE_SCALE * gCanvasAspectRatio;
let planeY = gPlane.posY + gPlane.plane_frames[0].height / 2 * PLANE_SCALE * gCanvasAspectRatio;
let spikeDownX = this.x - worldPos + this.spikeDown.width * 0.61 * gCanvasAspectRatio;
let spikeDownY = -this.gap / 2 - this.height_offset + this.spikeDown.height * gCanvasAspectRatio;
let spikeUpX = this.x - worldPos + this.spikeUp.width * 0.61 * gCanvasAspectRatio;
let spikeUpY = gCanvasHeight - this.spikeUp.height * gCanvasAspectRatio + this.gap / 2 - this.height_offset;
gDynamicContext.beginPath();
gDynamicContext.fillRect(spikeDownX - 3, spikeDownY - 3, 6, 6);
gDynamicContext.stroke();
gDynamicContext.beginPath();
gDynamicContext.fillRect(spikeUpX - 3, spikeUpY - 3, 6, 6);
gDynamicContext.stroke();
let spikeDownA = [this.x - worldPos, - this.gap / 2 - this.height_offset];
let spikeDownB = [spikeDownX, spikeDownY];
let spikeUpA = [this.x - worldPos, gCanvasHeight + this.gap / 2 - this.height_offset];
let spikeUpB = [spikeUpX, spikeUpY];
gDynamicContext.beginPath();
gDynamicContext.moveTo(spikeDownA[0], spikeDownA[1]);
gDynamicContext.lineTo(spikeDownB[0], spikeDownB[1]);
gDynamicContext.stroke();
gDynamicContext.beginPath();
gDynamicContext.moveTo(spikeUpA[0], spikeUpA[1]);
gDynamicContext.lineTo(spikeUpB[0], spikeUpB[1]);
gDynamicContext.stroke();
}
}
// Sets a random gap and height for this spike pair
setRandomGapAndHeight(gapMinMax, heightMinMax){
this.gap = this.randomBetween(gapMinMax[0], gapMinMax[1]);
this.height_offset = this.randomBetween(heightMinMax[0], heightMinMax[1]);
}
// Whether the provided circle collides with the upper or lower spike
isCollidingWithCircle(x, y, r, worldPos){
// Check spike tip
let spikeDownX = this.x - worldPos + this.spikeDown.width * 0.61 * gCanvasAspectRatio;
let spikeDownY = -this.gap / 2 - this.height_offset + this.spikeDown.height * gCanvasAspectRatio;
let spikeUpX = this.x - worldPos + this.spikeUp.width * 0.61 * gCanvasAspectRatio;
let spikeUpY = gCanvasHeight - this.spikeUp.height * gCanvasAspectRatio + this.gap / 2 - this.height_offset;
if(Math.pow(spikeDownX - x, 2) + Math.pow(spikeDownY - y, 2) < (r * r) ||
Math.pow(spikeUpX - x, 2) + Math.pow(spikeUpY - y, 2) < (r * r)){
return true;
}
// Check spike edge
// Using projection and distance to the projection point
let spikeDownA = [this.x - worldPos, - this.gap / 2 - this.height_offset];
let spikeDownB = [spikeDownX, spikeDownY];
let spikeUpA = [this.x - worldPos, gCanvasHeight + this.gap / 2 - this.height_offset];
let spikeUpB = [spikeUpX, spikeUpY];
let planeVector = [x - spikeDownA[0], y - spikeDownA[1]];
let spikeDownVector = [spikeDownB[0] - spikeDownA[0], spikeDownB[1] - spikeDownA[1]]
let spikeUpVector = [spikeUpB[0] - spikeUpA[0], spikeUpB[1] - spikeUpA[1]]
let dotPart = this.dot(planeVector, spikeDownVector) / this.dot(spikeDownVector, spikeDownVector);
let projectionVector = [spikeDownVector[0] * dotPart, spikeDownVector[1] * dotPart];
let spikeDownProjectionPoint = [projectionVector[0] + spikeDownA[0], projectionVector[1] + spikeDownA[1]];
planeVector = [x - spikeUpA[0], y - spikeUpA[1]];
dotPart = this.dot(planeVector, spikeUpVector) / this.dot(spikeUpVector, spikeUpVector);
projectionVector = [spikeUpVector[0] * dotPart, spikeUpVector[1] * dotPart];
let spikeUpProjectionPoint = [projectionVector[0] + spikeUpA[0], projectionVector[1] + spikeUpA[1]];
if((spikeDownProjectionPoint[1] < spikeDownY &&
Math.pow(spikeDownProjectionPoint[0] - x, 2) + Math.pow(spikeDownProjectionPoint[1] - y, 2) < (r * r)) ||
(spikeUpProjectionPoint[1] > spikeUpY &&
Math.pow(spikeUpProjectionPoint[0] - x, 2) + Math.pow(spikeUpProjectionPoint[1] - y, 2) < (r * r))){
return true;
}
}
randomBetween(min, max) {
return Math.random() * (max - min) + min;
}
// See: https://stackoverflow.com/a/64816824/13599159
dot(a, b) {
return a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);
}
}
// Player controlled plane class
class Plane{
constructor(plane_frame1, plane_frame2, plane_frame3, animationSpeed){
this.plane_frames = [];
this.plane_frames.push(plane_frame1);
this.plane_frames.push(plane_frame2);
this.plane_frames.push(plane_frame3);
this.currentFrameIndex = 0;
this.worldPosX = 0;
this.startX = gCanvasWidth / 2 - plane_frame1.width / 2 - PLANE_OFFSET;
this.startY = gCanvasHeight / 3;
this.posX = this.startX;
this.posY = this.startY;
this.animationAccumulator = 0;
this.animationStep = animationSpeed / this.plane_frames.length;
this.velocity = 0;
this.isDying = false;
this.dead = false;
}
// Resets all necessary data
reset(){
this.currentFrameIndex = 0;
this.worldPosX = 0;
this.posX = this.startX;
this.posY = this.startY;
this.animationAccumulator = 0;
this.velocity = 0;
this.isDying = false;
this.dead = false;
}
update(delta){
// Skip if already dead
if(this.dead){
return;
}
// Apply velocity to y
this.posY += this.velocity * delta;
// Add gravity
this.velocity += GRAVITY * delta;
// Check whether the plane reached the ground
if(this.posY > gCanvasHeight - gGround.height * gGround.aspectRatio){
// If the player reached the ground before dying, let him die
if(!this.isDying){
this.die();
this.dead = true;
setTimeout(() => this.setDead(), PLAYER_DEAD_FROM_GROUND_DELAY * 1000)
}else {
this.setDead();
}
}
}
draw(context, scale, delta){
// Only stop animation if in game over screen
if(gGameState != GameState.GAME_OVER){
// Get current frame depending on animation progress
this.animationAccumulator += delta;
if(this.animationAccumulator >= this.animationStep){
this.currentFrameIndex = ++this.currentFrameIndex % this.plane_frames.length;
this.animationAccumulator -= this.animationStep
}
}
// Render current frame
var currentFrame = this.plane_frames[this.currentFrameIndex];
currentFrame.draw(context, this.posX, this.posY, scale);
// Display collision circle
if(SHOW_COLLISION_SHAPES){
gDynamicContext.beginPath();
gDynamicContext.arc(this.posX + this.plane_frames[0].width / 4 * gCanvasAspectRatio,
this.posY + this.plane_frames[0].height / 4 * gCanvasAspectRatio,
PLANE_CIRCLE_COLLISION_RADIUS, 0, 2 * Math.PI);
gDynamicContext.stroke();
}
}
// Shows the screen flash effect
die(){
this.velocity = 0;
this.isDying = true;
showScreenFlash(SCREEN_FLASH_DURATION, SCREEN_FLASH_REFRESH_RATE);
}
// Locks the plane and updates the gameState
setDead(){
// Reset velocity
this.velocity = 0;
this.dead = true;
// Tell game that player died
gGameState = GameState.GAME_OVER;
}
// Jump action
jump(){
// Skip if in the process of dying (or if dead)
if(this.isDying){
return;
}
// Prevent player from flying to the moon
if(gPlane.posY > 0){
gPlane.velocity = -PLANE_JUMP_VELOCITY;
}
}
}
</script>
</body>
</html>