-
Notifications
You must be signed in to change notification settings - Fork 54
/
index.html
683 lines (583 loc) · 33.1 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
<html>
<!--
HUE JUMPER - By Frank Force
Low fi retro inspired endless runner in only 2 kilobytes!
Features
- Retro style 3D rendering engine in full HD
- Realistic driving physics and collisions
- Random level generation with increasing difficulty
- Gradient sky with sun and moon
- Procedurally generated mountain range
- Random trees and rocks
- Camera rumble and slow when off road
- Checkpoint system, road markers, and hue shift
- Time and distance display
Minification notes
- remove all debug stuff, keyboard, pointer lock and touch control
- move variables to the top, combine where possible
- move start level to bottom outside function
- google closure https://xem.github.io/terser-online/
- terser https://xem.github.io/terser-online/
- golf code
- replace functions/return with =>
- use string templates
- use default params instead of void checks
- use ** instead of math.pow
- get rid of vars when possible
- don't try to eliminate repetition
- many tiny things that add up
- wrap the code in an onload string
- zip with adv zip -z -4 -i 1000
- say a payer to the gods of tinycode
- the result should be under 2k
-->
<title>Hue Jumper</title>
<meta charset="utf-8">
<body bgcolor=#000>
<canvas id=c style='touch-action:none;position:absolute;left:0px;top:0px;width:100%;height:100%'></canvas>
<a hidden id=downloadLink></a>
<script>
'use strict'; // strict mode
// debug settings
const debug = 0; // enable debug features
const usePointerLock = 1; // remove pointer lock for 2k build
// draw settings
const context = c.getContext('2d'); // canvas 2d context
const drawDistance = 800; // how many road segments to draw in front of player
const cameraDepth = 1; // FOV of camera (1 / Math.tan((fieldOfView/2) * Math.PI/180))
const roadSegmentLength = 100; // length of each road segment
const roadWidth = 500; // how wide is road
const warningTrackWidth = 150; // with of road plus warning track
const dashLineWidth = 9; // width of the dashed line in the road
const maxPlayerX = 2e3; // player can not move this far from center of road
const mountainCount = 30; // how many mountains are there
// player settings
const playerHeight = 150; // how high is player above ground
const playerMaxSpeed = 300; // limit max player speed
const playerAccel = 1; // player acceleration
const playerBrake = -3; // player acceleration when breaking
const playerTurnControl = .2; // player turning rate
const playerJumpSpeed = 25; // z speed added for jump
const playerSpringConstant = .01; // spring players pitch
const playerCollisionSlow = .1; // slow down from collisions
const pitchLerp = .1; // speed that camera pitch changes
const pitchSpringDamping = .9; // dampen the pitch spring
const elasticity = 1.2; // bounce elasticity (2 is full bounce, 1 is none)
const centrifugal = .002; // how much to pull player on turns
const forwardDamping = .999; // dampen player z speed
const lateralDamping = .7; // dampen player x speed
const offRoadDamping = .98; // more damping when off road
const gravity = -1; // gravity to apply in y axis
const cameraHeadingScale = 2; // scale of player turning to rotate camera
const worldRotateScale = .00005; // how much to rotate world around turns
// level settings
const maxTime = 20; // time to start with
const checkPointTime = 10; // how much time for getting to checkpoint
const checkPointDistance = 1e5; // how far between checkpoints
const checkpointMaxDifficulty = 9; // how many checkpoints before max difficulty
const roadEnd = 1e4; // how many sections until end of the road
// game variables
let playerPos; // player position 3d vector
let playerVelocity; // player velocity 3d vector
let playerPitchSpring; // spring for player pitch bounce
let playerPitchSpringVelocity; // velocity of pitch spring
let playerPitchRoad; // pitch of road, or 0 if player is in air
let playerAirFrame; // how many frames player has been in air
let worldHeading; // heading to turn skybox
let randomSeed; // random seed for level
let startRandomSeed; // save the starting seed for active use
let nextCheckPoint; // distance of next checkpoint
let hueShift; // current hue shift for all hsl colors
let road; // the list of road segments
let time; // time left before game over
function StartLevel()
{
/////////////////////////////////////////////////////////////////////////////////////
// build the road with procedural generation
/////////////////////////////////////////////////////////////////////////////////////
// set random seed & time
let roadGenSectionDistanceMax = 500; // start road with a straight part & init time
let roadGenWidth = roadWidth; // starting road width
let roadGenSectionDistance = 0; // distance left for this section
let roadGenTaper = 0; // length of taper
let roadGenWaveFrequencyX = 0; // X wave frequency
let roadGenWaveFrequencyY = 0; // Y wave frequency
let roadGenWaveScaleX = 0; // X wave amplitude (turn size)
let roadGenWaveScaleY = 0; // Y wave amplitude (hill size)
startRandomSeed = randomSeed = Date.now(); // set random seed
road = []; // clear list of road segments
// generate the road
for(let i = 0; i < roadEnd*2; ++i) // generate every section of road
{
// make wavy hills
const x = Math.sin(i*roadGenWaveFrequencyX) * roadGenWaveScaleX; // road X
const y = Math.sin(i*roadGenWaveFrequencyY) * roadGenWaveScaleY; // road Y
// get or make the road gen segment
road[i] = road[i]? road[i] : {x:x, y:y, w:roadGenWidth}; // get road segment
// apply taper
const p = Clamp(roadGenSectionDistance / roadGenTaper, 0, 1); // get taper percent
road[i].x = Lerp(p, road[i].x, x); // X pos and taper
road[i].y = Lerp(p, road[i].y, y); // Y pos and taper
road[i].z = i*roadSegmentLength; // Z pos
road[i].w = i > roadEnd ? 0 : Lerp(p, road[i].w, roadGenWidth); // check for road end, width and taper
// get pitch angle and object pos
road[i].a = road[i-1]? Math.atan2(road[i-1].y-road[i].y, roadSegmentLength) : 0; // pitch angle
road[i].o = Random()<.2 && i > 9? 2*roadWidth * Random(10,-10) * Random(9) : 0; // object (tree or rock)
if (roadGenSectionDistance++ > roadGenSectionDistanceMax) // check for end of section
{
// calculate difficulty percent
const difficulty = Min(1, i*roadSegmentLength/checkPointDistance/checkpointMaxDifficulty); // difficulty
// randomize rotate settings
roadGenWidth = roadWidth*Random(1-difficulty*.7,3-2*difficulty); // road width
roadGenWaveFrequencyX = Random(Lerp(difficulty,0.01,.02)); // X frequency
roadGenWaveFrequencyY = Random(Lerp(difficulty,0.01,.03)); // Y frequency
roadGenWaveScaleX = i > roadEnd ? 0 : Random(Lerp(difficulty,.2,.5)); // X scale
roadGenWaveScaleY = Random(Lerp(difficulty,1e3,2e3)); // Y scale
// apply taper and move back
worldHeading = roadGenTaper = Random(99,500)|0; // randomize world heading and taper
roadGenSectionDistanceMax = roadGenTaper + Random(99,500); // randomize segment distance
i -= roadGenTaper; // subtract taper
roadGenSectionDistance = 0; // reset section distance
}
}
/////////////////////////////////////////////////////////////////////////////////////
// init game
/////////////////////////////////////////////////////////////////////////////////////
// reset everything to 0
playerVelocity = new Vector3
(
playerPitchSpring =
playerPitchSpringVelocity =
playerPitchRoad =
mouseWasPressed =
hueShift = 0
);
playerPos = new Vector3(road[0].x, road[0].y + playerHeight); // set player pos to match road
playerPitchRoad = road[0].a; // set player angle to match road
nextCheckPoint = checkPointDistance; // init next checkpoint
time = maxTime; // set the starting time
}
function Update()
{
// start frame
if (snapshot) {c.width|0} else // DEBUG REMOVE FROM MINFIED
c.width = window.innerWidth,c.height = window.innerHeight; // clear the screen and set size
if (!c || !c.width) // REMOVE FROM MINFIED
{
// fix bug on itch, wait for canvas before updating
requestAnimationFrame(Update);
return;
}
UpdateDebugPre(); // DEBUG REMOVE FROM MINFIED
/////////////////////////////////////////////////////////////////////////////////////
// update player - controls and physics
/////////////////////////////////////////////////////////////////////////////////////
// get player road segment
const playerRoadSegment = playerPos.z/roadSegmentLength|0; // current player road segment
const playerRoadSegmentPercent = playerPos.z/roadSegmentLength%1; // how far player is along current segment
// get lerped values between last and current road segment
const playerRoadX = Lerp(playerRoadSegmentPercent, road[playerRoadSegment].x, road[playerRoadSegment+1].x);
const playerRoadY = Lerp(playerRoadSegmentPercent, road[playerRoadSegment].y, road[playerRoadSegment+1].y) + playerHeight;
const roadPitch = Lerp(playerRoadSegmentPercent, road[playerRoadSegment].a, road[playerRoadSegment+1].a);
const playerVelocityLast = playerVelocity.Add(0); // save last velocity
playerVelocity.y += gravity // gravity
playerVelocity.x *= lateralDamping; // apply lateral damping
playerVelocity.z = Max(0, time ? forwardDamping*playerVelocity.z : 0); // apply damping, prevent moving backwards
playerPos = playerPos.Add(playerVelocity); // add player velocity
const playerTurnAmount = (mouseX/window.innerWidth*2-1) * // update player turning and centrifugal motion
Lerp(playerVelocity.z/playerMaxSpeed, playerTurnControl, 0); // lerp off turning as max speed approaches
playerVelocity.x += // update x velocity
playerVelocity.z * playerTurnAmount - // apply turn
playerVelocity.z ** 2 * centrifugal * playerRoadX; // apply centrifugal force
playerPos.x = Clamp(playerPos.x, -maxPlayerX, maxPlayerX); // limit player x position
// check if on ground
if (playerPos.y < playerRoadY)
{
// bounce velocity against ground normal
playerPos.y = playerRoadY; // match y to ground plane
playerVelocity = new Vector3(0, Math.cos(roadPitch), Math.sin(roadPitch)) // get ground normal
.Multiply(-elasticity * // apply bounce
(Math.cos(roadPitch) * playerVelocity.y + Math.sin(roadPitch) * playerVelocity.z)) // dot of road and velocity
.Add(playerVelocity); // add velocity
playerAirFrame = 0; // reset air grace frames
playerVelocity.z +=
mouseDown? playerBrake : // apply brake
Lerp(playerVelocity.z/playerMaxSpeed, mouseWasPressed*playerAccel, 0); // apply accel
if (Math.abs(playerPos.x) > road[playerRoadSegment].w) // check if off road
{
playerVelocity.z *= offRoadDamping; // slow down when offroad
playerPitchSpring += Math.sin(playerPos.z/99)**4/99; // bump when offroad
}
}
// update jump
if (playerAirFrame++<6 && mouseDown && mouseUpFrames && mouseUpFrames<9 && time) // check for jump
{
playerVelocity.y += playerJumpSpeed; // apply jump velocity
playerAirFrame = 9; // prevent jumping again
}
mouseUpFrames = mouseDown? 0 : mouseUpFrames+1; // update mouse up frames for double click
const airPercent = (playerPos.y-playerRoadY)/99; // calculate above ground percent
playerPitchSpringVelocity += Lerp(airPercent,0,playerVelocity.y/4e4); // pitch down with vertical velocity
// update player pitch
playerPitchSpringVelocity += (playerVelocity.z - playerVelocityLast.z)/2e3; // pitch down with forward accel
playerPitchSpringVelocity -= playerPitchSpring * playerSpringConstant; // apply pitch spring constant
playerPitchSpringVelocity *= pitchSpringDamping; // dampen pitch spring
playerPitchSpring += playerPitchSpringVelocity; // update pitch spring
playerPitchRoad = Lerp(pitchLerp, playerPitchRoad, Lerp(airPercent,-roadPitch,0));// match pitch to road
const playerPitch = playerPitchSpring + playerPitchRoad; // update player pitch
/////////////////////////////////////////////////////////////////////////////////////
// draw background - sky, sun/moon, mountains, and horizon
/////////////////////////////////////////////////////////////////////////////////////
// multi use local variables
let x, y, w, i;
// pre calculate projection scale, flip y because y+ is down on canvas
const projectScale = (new Vector3(1, -1, 1)).Multiply(c.width/2/cameraDepth); // get projection scale
randomSeed = startRandomSeed; // set start seed
worldHeading = ClampAngle(worldHeading + playerVelocity.z * playerRoadX * worldRotateScale); // update world angle
const cameraHeading = playerTurnAmount * cameraHeadingScale; // turn camera with player
const cameraOffset = Math.sin(cameraHeading)/2; // apply heading with offset
// draw sky
const brightness = Math.cos(worldHeading); // brighess from sun
const horizon = c.height/2 - Math.tan(playerPitch) * projectScale.y; // get horizion line
const g = context.createLinearGradient(0,horizon-c.height/2,0,horizon); // linear gradient for sky
g.addColorStop(0,LSHA(39+brightness*25,49+brightness*19,230-brightness*19)); // top sky color
g.addColorStop(1,LSHA(5,79,250-brightness*9)); // bottom sky color
DrawPoly(c.width/2, 0, c.width/2, c.width/2, c.height, c.width/2, g); // draw sky
// draw sun and moon
for(i=2; i--; ) // 0 is sun, 1 is moon
{
const g = context.createRadialGradient( // radial gradient for sun
x = c.width*(.5+Lerp( // angle 0 is center
(worldHeading/Math.PI/2+.5+i/2)%1, // sun angle percent
4, -4)-cameraOffset), // sun x pos, move far away for wrap
y = horizon - c.height/3, // sun y pos
c.width/25, // sun size
x, y, i?c.width/23:c.width); // sun end pos & size
g.addColorStop(0, LSHA(i?70:99)); // sun start color
g.addColorStop(1, LSHA(0,0,0,0)); // sun end color
DrawPoly(c.width/2, 0, c.width/2, c.width/2, c.height, c.width/2, g); // draw sun
}
// draw mountains
for(i = mountainCount; i--; ) // draw every mountain
{
const angle = ClampAngle(worldHeading+Random(19)); // mountain random angle
const lighting = Math.cos(angle-worldHeading); // mountain lighting
DrawPoly(
x = c.width*(.5+Lerp(angle/Math.PI/2+.5, 4, -4)-cameraOffset), // mountain x pos, move far away for wrap
y = horizon, // mountain base
w = Random(.2,.8)**2*c.height, // mountain width
x+w*Random(-.5,.5), // random tip skew
y - Random(.5,.8)*w, 0, // mountain height
LSHA(Random(15,25)+i/3-lighting*9,i/2+Random(19),Random(220,230))); // mountain color
}
// draw horizon
DrawPoly(c.width/2, horizon, c.width/2, c.width/2, c.height, c.width/2, // horizon pos & size
LSHA(25, 30, 95)); // horizon color
/////////////////////////////////////////////////////////////////////////////////////
// draw road and objects
/////////////////////////////////////////////////////////////////////////////////////
// calcuate road x offsets and projections (iterate in reverse)
for(x = w = i = 0; i < drawDistance+1; ) // for every section in draw range
{
// create road world position
let p = new Vector3( // set road position
x += w += road[playerRoadSegment+i].x, // sum local road offsets
road[playerRoadSegment+i].y, road[playerRoadSegment+i].z) // road y and z pos
.Add(playerPos.Multiply(-1)); // subtract to get local space
p.x = p.x*Math.cos(cameraHeading) - p.z*Math.sin(cameraHeading); // rotate camera heading
// tilt camera pitch
const z = 1 / (p.z*Math.cos(playerPitch) - p.y*Math.sin(playerPitch)); // invert z for projection
p.y = p.y*Math.cos(playerPitch) - p.z*Math.sin(playerPitch);
p.z = z;
// project road segment to canvas space
road[playerRoadSegment+i++].p = // set projected road point
p.Multiply(new Vector3(z, z, 1)) // projection
.Multiply(projectScale) // scale
.Add(new Vector3(c.width/2,c.height/2)) // center on canvas
}
// draw the road segments
let segment2 = road[playerRoadSegment+drawDistance]; // store the last segment
for(i = drawDistance; i--; ) // iterate through the draw distance
{
const segment1 = road[playerRoadSegment+i];
randomSeed = startRandomSeed + playerRoadSegment + i; // random seed for this segment
const lighting = Math.sin(segment1.a) * Math.cos(worldHeading)*99; // calculate segment lighting
const p1 = segment1.p; // projected point
const p2 = segment2.p; // last projected point
if (p1.z < 1e5 && p1.z > 0) // check near and far clip
{
if (i % (Lerp(i/drawDistance,1,9)|0) == 0) // fade in road resolution
{
// ground
DrawPoly(c.width/2, p1.y, c.width/2, c.width/2, p2.y, c.width/2, // ground top & bottom
LSHA(25+lighting, 30, 95)); // ground color
// warning track
if (segment1.w > 400) // no warning track if thin
DrawPoly(p1.x, p1.y, p1.z*(segment1.w+warningTrackWidth), // warning track top
p2.x, p2.y, p2.z*(segment2.w+warningTrackWidth), // warning track bottom
LSHA(((i+playerRoadSegment)%19<9? 50: 20)+lighting)); // warning track stripe color
// road
DrawPoly(p1.x, p1.y, p1.z*segment1.w, // road top
p2.x, p2.y, p2.z*segment2.w, // road bottom
LSHA((segment1.z%checkPointDistance < 500 ? 70 : 7)+lighting)); // road color and checkpoint
// dashed lines
if (segment1.w > 300) // no dash lines if very thin
(i+playerRoadSegment)%9==0 && i < drawDistance/3 && // make dashes and skip if far out
DrawPoly(p1.x, p1.y, p1.z*dashLineWidth, // dash lines top
p2.x, p2.y, p2.z*dashLineWidth, // dash lines botom
LSHA(70+lighting)); // dash lines color
segment2 = segment1; // prep for next segment
}
// draw and update road object
if (segment1.o) // check for road object
{
// player object collision check
const height = (Random(2)|0) * 400; // object type & height
if (!segment1.h // prevent hitting the same object
&& Math.abs(playerPos.x - segment1.o) < 200 // player collison x
&& Math.abs(playerPos.z + roadSegmentLength - segment1.z) < 200 // check ahead player collison z
&& playerPos.y-playerHeight < segment1.y+150+height) // player y collision
{
playerVelocity = playerVelocity.Multiply(segment1.h = playerCollisionSlow); // stop player and mark hit
}
// draw road object
const alpha = Lerp(i/drawDistance, 4, 0); // fade in object alpha
if (height) // tree
{
DrawPoly(x = p1.x+p1.z * segment1.o, p1.y, p1.z*29, // trunk bottom
x, p1.y-99*p1.z, p1.z*29, // trunk top
LSHA(5+Random(9), 50+Random(9), 29+Random(9), alpha)); // trunk color
DrawPoly(x, p1.y-Random(50,99)*p1.z, p1.z*Random(199,250), // leaves bottom
x, p1.y-Random(600,800)*p1.z, 0, // leaves top
LSHA(25+Random(9), 80+Random(9), 9+Random(29), alpha)); // leaves color
}
else // rock
{
DrawPoly(x = p1.x+p1.z * segment1.o, p1.y, p1.z*Random(200,250), // rock bottom
x+p1.z*(Random(99,-99)), p1.y-Random(200,250)*p1.z, p1.z*Random(99), // rock top
LSHA(55+Random(9), 30+Random(9), 209+Random(9), alpha)); // rock color
}
}
}
}
UpdateDebugPost(); // DEBUG REMOVE FROM MINFIED
/////////////////////////////////////////////////////////////////////////////////////
// draw and update time and checkpoints
/////////////////////////////////////////////////////////////////////////////////////
if (playerPos.z > nextCheckPoint) // crossed checkpoint
{
time += checkPointTime; // add more time
nextCheckPoint += checkPointDistance; // set next checkpoint
hueShift += 36; // shift hue
}
context.font = '8em"'; // set font size
context.fillStyle = LSHA(99,0,0,.5); // set font
if (mouseWasPressed)
{
time = Clamp(time - 1/60, 0, maxTime); // update and clamp time
// show time
context.fillText(Math.ceil(time), 9,99); // draw time text
context.strokeText(Math.ceil(time), 9,99); // draw time text outline
// show distance
context.textAlign = 'right'; // set right alignment for distance
context.fillText(0|playerPos.z/1e3, c.width-9, 99); // draw distance text
context.strokeText(0|playerPos.z/1e3, c.width-9, 99); // draw distance text outline
}
else
{
// show title
context.textAlign = 'center'; // set center alignment for distance
context.fillText('𝙃𝙐𝙀 𝙅𝙐𝙈𝙋𝙀𝙍', c.width/2, 99); // draw title text
context.strokeText('𝙃𝙐𝙀 𝙅𝙐𝙈𝙋𝙀𝙍', c.width/2, 99); // draw distance title outline
}
// kick off next frame
requestAnimationFrame(Update);
}
/////////////////////////////////////////////////////////////////////////////////////
// math and helper functions
/////////////////////////////////////////////////////////////////////////////////////
const LSHA = (l, s=0, h=0, a=1) =>`hsl(${h+hueShift},${s}%,${l}%,${a})`;
const Min = (v, min) => v<min ? v : min;
const Max = (v, max) => v>max ? v : max;
const Clamp = (v, min, max) => Min(Max(v, min), max);
const Lerp = (p, a, b) => a + Clamp(p, 0, 1) * (b-a);
const ClampAngle = a => (a+Math.PI) % (2*Math.PI) + (a+Math.PI<0? Math.PI : -Math.PI);
const Random = (max=1, min=0) => Lerp((Math.sin(++randomSeed)+1)*1e5%1, min, max);
// simple 3d vector class
class Vector3
{
constructor(x=0, y=0, z=0) { this.x = x; this.y = y; this.z = z }
Add(v) { v = isNaN(v) ? v : new Vector3(v,v,v); return new Vector3( this.x + v.x, this.y + v.y, this.z + v.z); }
Multiply(v) { v = isNaN(v) ? v : new Vector3(v,v,v); return new Vector3( this.x * v.x, this.y * v.y, this.z * v.z); }
}
// draw a trapazoid shaped poly
function DrawPoly(x1, y1, w1, x2, y2, w2, fillStyle)
{
context.beginPath(context.fillStyle = fillStyle);
context.lineTo(x1-w1|0, y1|0);
context.lineTo(x1+w1|0, y1|0);
context.lineTo(x2+w2|0, y2|0);
context.lineTo(x2-w2|0, y2|0);
context.fill();
}
/////////////////////////////////////////////////////////////////////////////////////
// mouse input
/////////////////////////////////////////////////////////////////////////////////////
let mouseDown = 0;
let mouseWasPressed = 0;
let mouseUpFrames = 0;
let mouseX = window.innerWidth/2;
let mouseLockX = 0;
let touchMode = 0;
onmouseup = e => mouseDown = 0;
onmousedown = e =>
{
if (mouseWasPressed)
mouseDown = 1;
mouseWasPressed = 1;
if (usePointerLock && e.button == 0 && document.pointerLockElement !== c)
{
c.requestPointerLock = c.requestPointerLock || c.mozRequestPointerLock;
c.requestPointerLock();
mouseLockX = 0;
}
}
onmousemove = e =>
{
if (!usePointerLock)
{
mouseX = e.x;
return;
}
if (document.pointerLockElement !== c)
return;
// adjust for pointer lock
mouseLockX += e.movementX;
mouseLockX = Clamp(mouseLockX, -window.innerWidth/2, window.innerWidth/2);
// apply curve to input
const inputCurve = 1.5;
mouseX = mouseLockX;
mouseX /= window.innerWidth/2;
mouseX = Math.sign(mouseX) * (1-(1-Math.abs(mouseX))**inputCurve);
mouseX *= window.innerWidth/2;
mouseX += window.innerWidth/2;
}
/////////////////////////////////////////////////////////////////////////////////////
// touch control
/////////////////////////////////////////////////////////////////////////////////////
if (typeof ontouchend != 'undefined')
{
let ProcessTouch = e =>
{
e.preventDefault();
mouseDown = !(e.touches.length > 0);
mouseWasPressed = 1;
if (mouseDown)
return;
// average all touch positions
let x = 0, y = 0;
for (let touch of e.touches)
{
x += touch.clientX;
y += touch.clientY;
}
mouseX = x/e.touches.length;
}
c.addEventListener('touchstart', ProcessTouch, false);
c.addEventListener('touchmove', ProcessTouch, false);
c.addEventListener('touchcancel', ProcessTouch, false);
c.addEventListener('touchend', ProcessTouch, false);
}
/////////////////////////////////////////////////////////////////////////////////////
// debug stuff
/////////////////////////////////////////////////////////////////////////////////////
let debugPrintLines;
let snapshot;
function UpdateDebugPre()
{
debugPrintLines = [];
if (inputWasPushed[82]) // R = restart
{
mouseLockX = 0;
StartLevel();
}
if (inputWasPushed[49]) // 1 = screenshot
{
snapshot = 1;
// use 1080p resolution
c.width = 1920;
c.height = 1080;
}
}
function UpdateDebugPost()
{
if (snapshot)
{
SaveSnapshot();
snapshot = 0;
}
UpdateInput();
if (!debug)
return;
UpdateFps();
context.font='2em"';
for (i in debugPrintLines)
{
let line = debugPrintLines[i];
context.fillStyle = line.color;
context.fillText(line.text,c.width/2,35+35*i);
}
}
function DebugPrint(text, color='#F00')
{
if (!debug)
return;
if (typeof text == 'object')
text += JSON.stringify(text);
let line = {text:text, color:color};
debugPrintLines.push(line);
}
function SaveSnapshot()
{
downloadLink.download="snapshot.png";
downloadLink.href=c.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream");
downloadLink.click();
}
/////////////////////////////////////////////////////////////////////////////////////
// frame rate counter
/////////////////////////////////////////////////////////////////////////////////////
let lastFpsMS = 0;
let averageFps = 0;
function UpdateFps()
{
let ms = performance.now();
let deltaMS = ms - lastFpsMS;
lastFpsMS = ms;
let fps = 1/(deltaMS/1e3);
averageFps = averageFps*.9 + fps*.1;
context.font='3em"';
context.fillStyle='#0007';
context.fillText(averageFps|0,c.width-90,c.height-40);
}
/////////////////////////////////////////////////////////////////////////////////////
// keyboard control
/////////////////////////////////////////////////////////////////////////////////////
let inputIsDown = [];
let inputWasDown = [];
let inputWasPushed = [];
onkeydown = e => inputIsDown[e.keyCode] = 1;
onkeyup = e => inputIsDown[e.keyCode] = 0;
function UpdateInput()
{
inputWasPushed = inputIsDown.map((e,i) => e && !inputWasDown[i]);
inputWasDown = inputIsDown.slice();
}
/////////////////////////////////////////////////////////////////////////////////////
// init hue jumper
/////////////////////////////////////////////////////////////////////////////////////
// startup and kick off update loop
StartLevel();
Update();
</script>
</body>
</html>