-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
642 lines (523 loc) · 20.1 KB
/
script.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
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r127/build/three.module.js';
import * as MODELS from './mscript.js';
const counterDOM = document.getElementById('counter');
const endDOM = document.getElementById('end');
const scene = new THREE.Scene();
const distance = 1000;
const camera = new THREE.OrthographicCamera( window.innerWidth/-2, window.innerWidth/2, window.innerHeight / 2, window.innerHeight / -2, 0.1, 10000 );
camera.rotation.x = 50*Math.PI/180;
camera.rotation.y = 20*Math.PI/180;
camera.rotation.z = 10*Math.PI/180;
var flag = true; //flag used to halt commands when the retry button overlays
const initialCameraPositionY = -Math.tan(camera.rotation.x)*distance;
const initialCameraPositionX = Math.tan(camera.rotation.y)*Math.sqrt(distance**2 + initialCameraPositionY**2);
camera.position.y = initialCameraPositionY;
camera.position.x = initialCameraPositionX;
camera.position.z = distance;
const zoom = 2;
const avatarSize = 15;
const positionWidth = 42;
const columns = 19;
const boardWidth = positionWidth*columns;
const stepTime = 250; // Miliseconds it takes for the chicken to take a step forward, backward, left or right
let lanes;
let currentLane;
let currentColumn;
let previousTimestamp;
let startMoving;
let moves;
let stepStartTimestamp;
const carFrontTexture = new Texture(40,80,[{x: 0, y: 10, w: 30, h: 60 }]);
const carBackTexture = new Texture(40,80,[{x: 10, y: 10, w: 30, h: 60 }]);
const carRightSideTexture = new Texture(110,40,[{x: 10, y: 0, w: 50, h: 30 }, {x: 70, y: 0, w: 30, h: 30 }]);
const carLeftSideTexture = new Texture(110,40,[{x: 10, y: 10, w: 50, h: 30 }, {x: 70, y: 10, w: 30, h: 30 }]);
const truckFrontTexture = new Texture(30,30,[{x: 15, y: 0, w: 10, h: 30 }]);
const truckRightSideTexture = new Texture(25,30,[{x: 0, y: 15, w: 10, h: 10 }]);
const truckLeftSideTexture = new Texture(25,30,[{x: 0, y: 5, w: 10, h: 10 }]);
const generateLanes = () => [-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9].map((index) => {
const lane = new Lane(index);
lane.mesh.position.y = index*positionWidth*zoom;
scene.add( lane.mesh );
return lane;
}).filter((lane) => lane.index >= 0);
const addLane = () => {
const index = lanes.length;
const lane = new Lane(index);
lane.mesh.position.y = index*positionWidth*zoom;
scene.add(lane.mesh);
lanes.push(lane);
}
var avatar = null;
var character = localStorage.getItem("character");
if(character == 1){
avatar = new MODELS.Chef();
avatar.mesh.position.z = 50;
avatar.mesh.rotation.y = 3;
}
else if (character == 2){
avatar = new MODELS.Pig();
avatar.mesh.position.z = 30;
avatar.mesh.rotation.y = 1.5;
}
else if (character == 3){
avatar = new MODELS.Penguin();
avatar.mesh.position.z = 40;
avatar.mesh.rotation.y = 1.7;
}
else{
avatar = new MODELS.Chicken();
avatar.mesh.position.z = 40;
avatar.mesh.rotation.y = 1.5;
}
avatar.mesh.rotation.x = 1.5;
avatar.mesh.scale.set(10, 10, 10);
//avatar.mesh.position.set(0,0,0);
scene.add( avatar.mesh );
var hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
scene.add(hemiLight)
const initialDirLightPositionX = -100;
const initialDirLightPositionY = -100;
var dirLight = new THREE.DirectionalLight(0xffffff, 0.6);
dirLight.position.set(initialDirLightPositionX, initialDirLightPositionY, 200);
dirLight.castShadow = true;
dirLight.target = avatar.mesh;
scene.add(dirLight);
dirLight.shadow.mapSize.width = 2048;
dirLight.shadow.mapSize.height = 2048;
var d = 500;
dirLight.shadow.camera.left = - d;
dirLight.shadow.camera.right = d;
dirLight.shadow.camera.top = d;
dirLight.shadow.camera.bottom = - d;
// var helper = new THREE.CameraHelper( dirLight.shadow.camera );
// var helper = new THREE.CameraHelper( camera );
// scene.add(helper)
var backLight = new THREE.DirectionalLight(0x000000, .4);
backLight.position.set(200, 200, 50);
backLight.castShadow = true;
scene.add(backLight)
const laneTypes = ['car', 'truck', 'forest'];
const laneSpeeds = [2, 3,4,10];
const vechicleColors = [0xa52523, 0xbdb638, 0x78b14b];
const threeHeights = [20,45,60];
const initaliseValues = () => {
counterDOM.innerHTML = 0;
lanes = generateLanes()
flag = true; // flag reset
currentLane = 0;
currentColumn = Math.floor(columns/2);
previousTimestamp = null;
startMoving = false;
moves = [];
stepStartTimestamp;
avatar.mesh.position.x = 0;
avatar.mesh.position.y = 0;
//avatar.mesh.rotation.y = (Math.Pi / 2);
camera.position.y = initialCameraPositionY;
camera.position.x = initialCameraPositionX;
dirLight.position.x = initialDirLightPositionX;
dirLight.position.y = initialDirLightPositionY;
}
initaliseValues();
const renderer = new THREE.WebGLRenderer({
alpha: true,
antialias: true
});
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
function Texture(width, height, rects) {
const canvas = document.createElement( "canvas" );
canvas.width = width;
canvas.height = height;
const context = canvas.getContext( "2d" );
context.fillStyle = "#ffffff";
context.fillRect( 0, 0, width, height );
context.fillStyle = "rgba(0,0,0,0.6)";
rects.forEach(rect => {
context.fillRect(rect.x, rect.y, rect.w, rect.h);
});
return new THREE.CanvasTexture(canvas);
}
function Wheel() {
const wheel = new THREE.Mesh(
new THREE.BoxBufferGeometry( 12*zoom, 33*zoom, 12*zoom ),
new THREE.MeshLambertMaterial( { color: 0x333333} )
);
wheel.position.z = 6*zoom;
return wheel;
}
function Car() {
const car = new THREE.Group();
const color = vechicleColors[Math.floor(Math.random() * vechicleColors.length)];
const main = new THREE.Mesh(
new THREE.BoxBufferGeometry( 60*zoom, 30*zoom, 15*zoom ),
new THREE.MeshPhongMaterial( { color } )
);
main.position.z = 15*zoom;
main.castShadow = true;
main.receiveShadow = true;
car.add(main)
const cabin = new THREE.Mesh(
new THREE.BoxBufferGeometry( 33*zoom, 24*zoom, 12*zoom ),
[
new THREE.MeshPhongMaterial( { color: 0xcccccc , map: carBackTexture } ),
new THREE.MeshPhongMaterial( { color: 0xcccccc , map: carFrontTexture } ),
new THREE.MeshPhongMaterial( { color: 0xcccccc , map: carRightSideTexture } ),
new THREE.MeshPhongMaterial( { color: 0xcccccc , map: carLeftSideTexture } ),
new THREE.MeshPhongMaterial( { color: 0xcccccc } ), // top
new THREE.MeshPhongMaterial( { color: 0xcccccc } ) // bottom
]
);
cabin.position.x = 6*zoom;
cabin.position.z = 25.5*zoom;
cabin.castShadow = true;
cabin.receiveShadow = true;
car.add( cabin );
const frontWheel = new Wheel();
frontWheel.position.x = -18*zoom;
car.add( frontWheel );
const backWheel = new Wheel();
backWheel.position.x = 18*zoom;
car.add( backWheel );
car.castShadow = true;
car.receiveShadow = false;
return car;
}
function Truck() {
const truck = new THREE.Group();
const color = vechicleColors[Math.floor(Math.random() * vechicleColors.length)];
const base = new THREE.Mesh(
new THREE.BoxBufferGeometry( 100*zoom, 25*zoom, 5*zoom ),
new THREE.MeshLambertMaterial( { color: 0xb4c6fc } )
);
base.position.z = 10*zoom;
truck.add(base)
const cargo = new THREE.Mesh(
new THREE.BoxBufferGeometry( 75*zoom, 35*zoom, 40*zoom ),
new THREE.MeshPhongMaterial( { color: 0xb4c6fc } )
);
cargo.position.x = 15*zoom;
cargo.position.z = 30*zoom;
cargo.castShadow = true;
cargo.receiveShadow = true;
truck.add(cargo)
const cabin = new THREE.Mesh(
new THREE.BoxBufferGeometry( 25*zoom, 30*zoom, 30*zoom ),
[
new THREE.MeshPhongMaterial( { color } ), // back
new THREE.MeshPhongMaterial( { color , map: truckFrontTexture } ),
new THREE.MeshPhongMaterial( { color , map: truckRightSideTexture } ),
new THREE.MeshPhongMaterial( { color , map: truckLeftSideTexture } ),
new THREE.MeshPhongMaterial( { color } ), // top
new THREE.MeshPhongMaterial( { color } ) // bottom
]
);
cabin.position.x = -40*zoom;
cabin.position.z = 20*zoom;
cabin.castShadow = true;
cabin.receiveShadow = true;
truck.add( cabin );
const frontWheel = new Wheel();
frontWheel.position.x = -38*zoom;
truck.add( frontWheel );
const middleWheel = new Wheel();
middleWheel.position.x = -10*zoom;
truck.add( middleWheel );
const backWheel = new Wheel();
backWheel.position.x = 30*zoom;
truck.add( backWheel );
return truck;
}
//TODO FIX tree textures
function Tree() {
const tree = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.BoxBufferGeometry( 15*zoom, 15*zoom, 20*zoom ),
new THREE.MeshPhongMaterial( { color: 0x964B00} )
);
trunk.position.z = 10*zoom;
trunk.castShadow = true;
trunk.receiveShadow = true;
tree.add(trunk);
var height = threeHeights[Math.floor(Math.random()*threeHeights.length)];
const crown = new THREE.Mesh(
new THREE.BoxBufferGeometry( 30*zoom, 30*zoom, height*zoom ),
new THREE.MeshLambertMaterial( { color: 0x006400 } )
);
crown.position.z = (height/2+20)*zoom;
crown.castShadow = true;
crown.receiveShadow = false;
tree.add(crown);
return tree;
}
function Road() {
const road = new THREE.Group();
const createSection = color => new THREE.Mesh(
new THREE.PlaneBufferGeometry( boardWidth*zoom, positionWidth*zoom ),
new THREE.MeshPhongMaterial( { color } )
);
const middle = createSection(0x454A59);
middle.receiveShadow = true;
road.add(middle);
const left = createSection(0x393D49);
left.position.x = - boardWidth*zoom;
road.add(left);
const right = createSection(0x393D49);
right.position.x = boardWidth*zoom;
road.add(right);
return road;
}
function Grass() {
const grass = new THREE.Group();
const createSection = color => new THREE.Mesh(
new THREE.BoxBufferGeometry( boardWidth*zoom, positionWidth*zoom, 3*zoom ),
new THREE.MeshPhongMaterial( { color } )
);
const middle = createSection(0xbaf455);
middle.receiveShadow = true;
grass.add(middle);
const left = createSection(0x99C846);
left.position.x = - boardWidth*zoom;
grass.add(left);
const right = createSection(0x99C846);
right.position.x = boardWidth*zoom;
grass.add(right);
grass.position.z = 1.5*zoom;
return grass;
}
function Lane(index) {
this.index = index;
this.type = index <= 0 ? 'field' : laneTypes[Math.floor(Math.random()*laneTypes.length)];
switch(this.type) {
case 'field': {
this.type = 'field';
this.mesh = new Grass();
break;
}
case 'forest': {
this.mesh = new Grass();
this.occupiedPositions = new Set();
this.threes = [1,2,3,4].map(() => {
const tree = new Tree();
let position;
do {
position = Math.floor(Math.random()*columns);
}while(this.occupiedPositions.has(position))
this.occupiedPositions.add(position);
tree.position.x = (position*positionWidth+positionWidth/2)*zoom-boardWidth*zoom/2;
this.mesh.add( tree );
return tree;
})
break;
}
case 'car' : {
this.mesh = new Road();
this.direction = Math.random() >= 0.5;
const occupiedPositions = new Set();
this.vechicles = [1,2,3].map(() => {
const vechicle = new Car();
let position;
do {
position = Math.floor(Math.random()*columns/2);
}while(occupiedPositions.has(position))
occupiedPositions.add(position);
vechicle.position.x = (position*positionWidth*2+positionWidth/2)*zoom-boardWidth*zoom/2;
if(!this.direction) vechicle.rotation.z = Math.PI;
this.mesh.add( vechicle );
return vechicle;
})
this.speed = laneSpeeds[Math.floor(Math.random()*laneSpeeds.length)];
break;
}
case 'truck' : {
this.mesh = new Road();
this.direction = Math.random() >= 0.5;
const occupiedPositions = new Set();
this.vechicles = [1,2].map(() => {
const vechicle = new Truck();
let position;
do {
position = Math.floor(Math.random()*columns/3);
}while(occupiedPositions.has(position))
occupiedPositions.add(position);
vechicle.position.x = (position*positionWidth*3+positionWidth/2)*zoom-boardWidth*zoom/2;
if(!this.direction) vechicle.rotation.z = Math.PI;
this.mesh.add( vechicle );
return vechicle;
})
this.speed = laneSpeeds[Math.floor(Math.random()*laneSpeeds.length)];
break;
}
}
}
document.getElementById('forward').addEventListener("click", () => move('forward'));
document.getElementById('backward').addEventListener("click", () => move('backward'));
document.getElementById('left').addEventListener("click", () => move('left'));
document.getElementById('right').addEventListener("click", () => move('right'));
window.addEventListener("keydown", event => {
if (!flag) //prevents the player to move the character using the key arrows
return;
if (event.keyCode == '38') {
// up arrow
move('forward');
}
else if (event.keyCode == '40') {
// down arrow
move('backward');
}
else if (event.keyCode == '37') {
// left arrow
move('left');
}
else if (event.keyCode == '39') {
// right arrow
move('right');
}
});
function move(direction) {
const finalPositions = moves.reduce((position,move) => {
if(move === 'forward') return {lane: position.lane+1, column: position.column};
if(move === 'backward') return {lane: position.lane-1, column: position.column};
if(move === 'left') return {lane: position.lane, column: position.column-1};
if(move === 'right') return {lane: position.lane, column: position.column+1};
}, {lane: currentLane, column: currentColumn})
if (direction === 'forward') {
if(lanes[finalPositions.lane+1].type === 'forest' && lanes[finalPositions.lane+1].occupiedPositions.has(finalPositions.column)) return;
if(!stepStartTimestamp) startMoving = true;
addLane();
}
else if (direction === 'backward') {
if(finalPositions.lane === 0) return;
if(lanes[finalPositions.lane-1].type === 'forest' && lanes[finalPositions.lane-1].occupiedPositions.has(finalPositions.column)) return;
if(!stepStartTimestamp) startMoving = true;
}
else if (direction === 'left') {
if(finalPositions.column === 0) return;
if(lanes[finalPositions.lane].type === 'forest' && lanes[finalPositions.lane].occupiedPositions.has(finalPositions.column-1)) return;
if(!stepStartTimestamp) startMoving = true;
}
else if (direction === 'right') {
if(finalPositions.column === columns - 1 ) return;
if(lanes[finalPositions.lane].type === 'forest' && lanes[finalPositions.lane].occupiedPositions.has(finalPositions.column+1)) return;
if(!stepStartTimestamp) startMoving = true;
}
moves.push(direction);
}
function animate(timestamp) {
requestAnimationFrame( animate );
if(!previousTimestamp) previousTimestamp = timestamp;
const delta = timestamp - previousTimestamp;
previousTimestamp = timestamp;
// Animate cars and trucks moving on the lane
lanes.forEach(lane => {
if(lane.type === 'car' || lane.type === 'truck') {
const aBitBeforeTheBeginingOfLane = -boardWidth*zoom/2 - positionWidth*2*zoom;
const aBitAfterTheEndOFLane = boardWidth*zoom/2 + positionWidth*2*zoom;
lane.vechicles.forEach(vechicle => {
if(lane.direction) {
vechicle.position.x = vechicle.position.x < aBitBeforeTheBeginingOfLane ? aBitAfterTheEndOFLane : vechicle.position.x -= lane.speed/16*delta;
}else{
vechicle.position.x = vechicle.position.x > aBitAfterTheEndOFLane ? aBitBeforeTheBeginingOfLane : vechicle.position.x += lane.speed/16*delta;
}
});
}
});
if(startMoving) {
stepStartTimestamp = timestamp;
startMoving = false;
avatar.setTicToc(19);
}
if(stepStartTimestamp) {
const moveDeltaTime = timestamp - stepStartTimestamp;
const moveDeltaDistance = Math.min(moveDeltaTime/stepTime,1)*positionWidth*zoom;
const jumpDeltaDistance = Math.sin(Math.min(moveDeltaTime/stepTime,1)*Math.PI)*8*zoom;
var adjustAvatarHeight = 0;
if (character == 0){adjustAvatarHeight = 10} //for the chicken
else if (character == 1 || character == 3)adjustAvatarHeight = 20; //for the chef or penguin
switch(moves[0]) {
case 'forward': {
const positionY = currentLane*positionWidth*zoom + moveDeltaDistance;
camera.position.y = initialCameraPositionY + positionY;
dirLight.position.y = initialDirLightPositionY + positionY;
avatar.mesh.position.y = positionY; // initial avatar position is 0
avatar.animationUp();
avatar.mesh.position.z = jumpDeltaDistance + 30 + adjustAvatarHeight;
break;
}
case 'backward': {
const positionY = currentLane*positionWidth*zoom - moveDeltaDistance
camera.position.y = initialCameraPositionY + positionY;
dirLight.position.y = initialDirLightPositionY + positionY;
avatar.mesh.position.y = positionY;
avatar.animationUp();
avatar.mesh.position.z = jumpDeltaDistance +30 + adjustAvatarHeight;
break;
}
case 'left': {
const positionX = (currentColumn*positionWidth+positionWidth/2)*zoom -boardWidth*zoom/2 - moveDeltaDistance;
camera.position.x = initialCameraPositionX + positionX;
dirLight.position.x = initialDirLightPositionX + positionX;
avatar.mesh.position.x = positionX; // initial avatar position is 0
avatar.mesh.position.z = jumpDeltaDistance +30 + adjustAvatarHeight;
avatar.animationUp();
break;
}
case 'right': {
const positionX = (currentColumn*positionWidth+positionWidth/2)*zoom -boardWidth*zoom/2 + moveDeltaDistance;
camera.position.x = initialCameraPositionX + positionX;
dirLight.position.x = initialDirLightPositionX + positionX;
avatar.mesh.position.x = positionX;
avatar.mesh.position.z = jumpDeltaDistance+30 + adjustAvatarHeight;
avatar.animationUp();
break;
}
}
// Once a step has ended
if(moveDeltaTime > stepTime) {
avatar.animationDown();
switch(moves[0]) {
case 'forward': {
currentLane++;
counterDOM.innerHTML = currentLane;
break;
}
case 'backward': {
currentLane--;
counterDOM.innerHTML = currentLane;
break;
}
case 'left': {
currentColumn--;
break;
}
case 'right': {
currentColumn++;
break;
}
}
moves.shift();
// If more steps are to be taken then restart counter otherwise stop stepping
stepStartTimestamp = moves.length === 0 ? null : timestamp;
}
}
// Hit test
if(lanes[currentLane].type === 'car' || lanes[currentLane].type === 'truck') {
const avatarMinX = avatar.mesh.position.x - avatarSize*zoom/2;
const avatarMaxX = avatar.mesh.position.x + avatarSize*zoom/2;
const vechicleLength = { car: 60, truck: 105}[lanes[currentLane].type];
lanes[currentLane].vechicles.forEach(vechicle => {
const carMinX = vechicle.position.x - vechicleLength*zoom/2;
const carMaxX = vechicle.position.x + vechicleLength*zoom/2;
if(avatarMaxX > carMinX && avatarMinX < carMaxX) {
endDOM.style.visibility = 'visible';
flag = false; //flag triggering
avatar.mesh.rotation.z =3;
avatar.mesh.rotation.y +=3;
}
});
}
renderer.render( scene, camera );
}
requestAnimationFrame( animate );