-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.html
More file actions
855 lines (796 loc) · 37.7 KB
/
game.html
File metadata and controls
855 lines (796 loc) · 37.7 KB
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
<script type="text/javascript">
var gk_isXlsx = false;
var gk_xlsxFileLookup = {};
var gk_fileData = {};
function filledCell(cell) {
return cell !== '' && cell != null;
}
function loadFileData(filename) {
if (gk_isXlsx && gk_xlsxFileLookup[filename]) {
try {
var workbook = XLSX.read(gk_fileData[filename], { type: 'base64' });
var firstSheetName = workbook.SheetNames[0];
var worksheet = workbook.Sheets[firstSheetName];
// Convert sheet to JSON to filter blank rows
var jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, blankrows: false, defval: '' });
// Filter out blank rows (rows where all cells are empty, null, or undefined)
var filteredData = jsonData.filter(row => row.some(filledCell));
// Heuristic to find the header row by ignoring rows with fewer filled cells than the next row
var headerRowIndex = filteredData.findIndex((row, index) =>
row.filter(filledCell).length >= filteredData[index + 1]?.filter(filledCell).length
);
// Fallback
if (headerRowIndex === -1 || headerRowIndex > 25) {
headerRowIndex = 0;
}
// Convert filtered JSON back to CSV
var csv = XLSX.utils.aoa_to_sheet(filteredData.slice(headerRowIndex)); // Create a new sheet from filtered array of arrays
csv = XLSX.utils.sheet_to_csv(csv, { header: 1 });
return csv;
} catch (e) {
console.error(e);
return "";
}
}
return gk_fileData[filename] || "";
}
</script><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Realistic Flight Simulator</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
#controls {
position: absolute;
top: 10px;
left: 10px;
color: white;
font-family: Arial, sans-serif;
background: rgba(0, 0, 0, 0.7);
padding: 10px;
border-radius: 5px;
}
#hud {
position: absolute;
top: 10px;
right: 10px;
color: white;
font-family: Arial, sans-serif;
background: rgba(0, 0, 0, 0.7);
padding: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="controls">
<p>Controls:</p>
<p>W: Move Forward | S: Move Backward</p>
<p>A: Move Left | D: Move Right</p>
<p>Up: Move Up | Down: Move Down</p>
<p>Space: Shoot</p>
<p><a href="/index.html" style="color: lightblue; text-decoration: underline;">Back to Homepage</a></p>
</div>
<div id="hud">
<p>Currency: <span id="currency">0</span> Coins</p>
<p>Speed: <span id="speed">0</span> m/s</p>
<p>Altitude: <span id="altitude">0</span> m</p>
<div id="healthBarContainer" style="margin-top:10px;">
<label style="color:#fff;">Health:</label>
<div style="background:#444; border-radius:6px; width:120px; height:16px; display:inline-block; vertical-align:middle;">
<div id="healthBar" style="background:#28a745; height:16px; border-radius:6px; width:100%;"></div>
</div>
<span id="healthValue" style="color:#fff; margin-left:6px;">100</span>
</div>
<div id="missionTracker" style="margin-top:10px; color:#fff;">
<strong>Mission:</strong> <span id="missionText">Destroy the enemy plane!</span>
</div>
<div id="roundReminder" style="margin-top:10px; color:#FFD700; font-weight:bold;">
<!-- Will be filled by JS -->
</div>
<canvas id="minimap" width="120" height="120" style="margin-top:10px; background:rgba(0,0,0,0.5); border-radius:8px; border:1px solid #fff;"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js"></script>
<script>
// Scene setup
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add lighting
const ambientLight = new THREE.AmbientLight(0x404040, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(0, 1, 1).normalize();
scene.add(directionalLight);
// Skybox
const skyboxGeometry = new THREE.SphereGeometry(500, 32, 32);
const skyboxMaterial = new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load('https://threejs.org/examples/textures/skyboxsun25degtest.png'),
side: THREE.BackSide
});
const skybox = new THREE.Mesh(skyboxGeometry, skyboxMaterial);
scene.add(skybox);
// Advanced Terrain: Add rivers, mountains, forests
const terrainSize = 1000;
const terrainSegments = 100;
const terrainGeometry = new THREE.PlaneGeometry(terrainSize, terrainSize, terrainSegments, terrainSegments);
const noise = new SimplexNoise();
const vertices = terrainGeometry.attributes.position.array;
for (let i = 0; i < vertices.length; i += 3) {
const x = vertices[i];
const z = vertices[i + 1];
// Mountains
let height = noise.noise2D(x / 100, z / 100) * 20;
// Add river (simple sine wave river)
if (Math.abs(z - 100 * Math.sin(x / 150)) < 10) height -= 10;
// Add forest (random bumps)
if (noise.noise2D(x / 30, z / 30) > 0.5) height += Math.random() * 2;
vertices[i + 2] = height;
}
terrainGeometry.computeVertexNormals();
const terrainMaterial = new THREE.MeshStandardMaterial({
color: 0x228B22,
roughness: 0.5,
metalness: 0.3
});
const terrain = new THREE.Mesh(terrainGeometry, terrainMaterial);
terrain.rotation.x = -Math.PI / 2;
terrain.position.y = -50;
scene.add(terrain);
// Forests: add simple tree models
for (let i = 0; i < 100; i++) {
const tree = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.2, 0.2, 2),
new THREE.MeshStandardMaterial({ color: 0x8B4513 })
);
trunk.position.y = 1;
tree.add(trunk);
const leaves = new THREE.Mesh(
new THREE.SphereGeometry(0.8, 8, 8),
new THREE.MeshStandardMaterial({ color: 0x228B22 })
);
leaves.position.y = 2.2;
tree.add(leaves);
// Place trees randomly, but not in the river
let x, z;
do {
x = Math.random() * terrainSize - terrainSize / 2;
z = Math.random() * terrainSize - terrainSize / 2;
} while (Math.abs(z - 100 * Math.sin(x / 150)) < 15);
tree.position.set(x, getTerrainHeight(x, z) + 1, z);
scene.add(tree);
}
// Dynamic Sky: Day-night cycle, fog, and weather
let skyColorDay = new THREE.Color(0x87CEEB);
let skyColorNight = new THREE.Color(0x0a0a2a);
let skyColorSunset = new THREE.Color(0xffcc99);
let skyPhase = 0; // 0 to 1, 0=day, 0.5=sunset, 1=night
let weather = "clear"; // "clear", "rain", "fog"
let weatherTimer = 0;
function updateSkyAndWeather(delta) {
// Day-night cycle
skyPhase += delta * 0.01;
if (skyPhase > 1) skyPhase = 0;
let color;
if (skyPhase < 0.4) color = skyColorDay.clone().lerp(skyColorSunset, skyPhase / 0.4);
else if (skyPhase < 0.6) color = skyColorSunset.clone().lerp(skyColorNight, (skyPhase - 0.4) / 0.2);
else color = skyColorNight.clone().lerp(skyColorDay, (skyPhase - 0.6) / 0.4);
renderer.setClearColor(color);
// Weather change every 30s
weatherTimer += delta;
if (weatherTimer > 30) {
weatherTimer = 0;
const r = Math.random();
if (r < 0.5) weather = "clear";
else if (r < 0.8) weather = "fog";
else weather = "rain";
}
// Fog
if (weather === "fog") {
scene.fog = new THREE.Fog(color, 30, 120);
} else {
scene.fog = null;
}
// Rain: add rain particles
if (weather === "rain") {
if (!scene.getObjectByName("rain")) {
const rainGeo = new THREE.BufferGeometry();
const rainCount = 500;
const rainPositions = new Float32Array(rainCount * 3);
for (let i = 0; i < rainCount; i++) {
rainPositions[i * 3] = Math.random() * 200 - 100;
rainPositions[i * 3 + 1] = Math.random() * 80 + 10;
rainPositions[i * 3 + 2] = Math.random() * 200 - 100;
}
rainGeo.setAttribute('position', new THREE.BufferAttribute(rainPositions, 3));
const rainMat = new THREE.PointsMaterial({ color: 0x66aaff, size: 0.5, transparent: true });
const rain = new THREE.Points(rainGeo, rainMat);
rain.name = "rain";
scene.add(rain);
}
// Animate rain
const rain = scene.getObjectByName("rain");
if (rain) {
const pos = rain.geometry.attributes.position;
for (let i = 0; i < pos.count; i++) {
pos.array[i * 3 + 1] -= 1;
if (pos.array[i * 3 + 1] < 0) pos.array[i * 3 + 1] = Math.random() * 80 + 10;
}
pos.needsUpdate = true;
}
} else {
const rain = scene.getObjectByName("rain");
if (rain) scene.remove(rain);
}
}
// Particle Effects: Explosions, smoke trails
function createExplosion(position) {
const group = new THREE.Group();
for (let i = 0; i < 20; i++) {
const particle = new THREE.Mesh(
new THREE.SphereGeometry(0.2, 6, 6),
new THREE.MeshBasicMaterial({ color: 0xffaa00 })
);
particle.position.copy(position);
group.add(particle);
// Animate outward
const dir = new THREE.Vector3(
Math.random() - 0.5,
Math.random() - 0.5,
Math.random() - 0.5
).normalize().multiplyScalar(Math.random() * 2 + 1);
particle.userData = { dir, start: performance.now() / 1000 };
}
group.name = "explosion";
scene.add(group);
setTimeout(() => scene.remove(group), 800);
}
// Smoke trail for player
const smokeParticles = [];
function addSmokeTrail() {
const smoke = new THREE.Mesh(
new THREE.SphereGeometry(0.15, 6, 6),
new THREE.MeshBasicMaterial({ color: 0x888888, transparent: true, opacity: 0.5 })
);
smoke.position.copy(airplaneGroup.position);
scene.add(smoke);
smokeParticles.push({ mesh: smoke, time: performance.now() / 1000 });
}
function updateSmokeTrail() {
const now = performance.now() / 1000;
for (let i = smokeParticles.length - 1; i >= 0; i--) {
const s = smokeParticles[i];
s.mesh.material.opacity -= 0.01;
if (now - s.time > 2 || s.mesh.material.opacity <= 0) {
scene.remove(s.mesh);
smokeParticles.splice(i, 1);
}
}
}
// Camera Effects: Shake and motion blur
let cameraShakeTime = 0;
function triggerCameraShake() {
cameraShakeTime = 0.5;
}
function updateCameraEffects() {
if (cameraShakeTime > 0) {
cameraShakeTime -= 0.016;
camera.position.x += (Math.random() - 0.5) * 0.5;
camera.position.y += (Math.random() - 0.5) * 0.5;
}
// Simple motion blur: overlay transparent black rectangle
if (!document.getElementById('motion-blur')) {
const blur = document.createElement('div');
blur.id = 'motion-blur';
blur.style.position = 'fixed';
blur.style.left = 0;
blur.style.top = 0;
blur.style.width = '100vw';
blur.style.height = '100vh';
blur.style.pointerEvents = 'none';
blur.style.background = 'rgba(0,0,0,0.07)';
blur.style.zIndex = 100;
document.body.appendChild(blur);
}
document.getElementById('motion-blur').style.opacity = (velocity.length() > 1.2 ? 1 : 0);
}
// Player airplane
const airplaneGroup = new THREE.Group();
const fuselageGeometry = new THREE.CylinderGeometry(0.5, 0.5, 5, 32);
const airplaneMaterial = new THREE.MeshPhongMaterial({
color: 0x808080,
shininess: 150,
specular: 0xaaaaaa
});
const fuselage = new THREE.Mesh(fuselageGeometry, airplaneMaterial);
fuselage.rotation.z = Math.PI / 2;
airplaneGroup.add(fuselage);
const wingGeometry = new THREE.BoxGeometry(8, 0.2, 1.5);
const wingMaterial = new THREE.MeshPhongMaterial({ color: 0xC0C0C0, shininess: 50 });
const leftWing = new THREE.Mesh(wingGeometry, wingMaterial);
leftWing.position.set(-2, 0, 0);
airplaneGroup.add(leftWing);
const rightWing = new THREE.Mesh(wingGeometry, wingMaterial);
rightWing.position.set(2, 0, 0);
airplaneGroup.add(rightWing);
const tailGeometry = new THREE.BoxGeometry(2, 0.1, 1);
const tailMaterial = new THREE.MeshPhongMaterial({ color: 0xC0C0C0, shininess: 50 });
const tail = new THREE.Mesh(tailGeometry, tailMaterial);
tail.position.set(0, 0, 2.5);
airplaneGroup.add(tail);
const vStabGeometry = new THREE.BoxGeometry(0.1, 1, 1);
const vStab = new THREE.Mesh(vStabGeometry, tailMaterial);
vStab.position.set(0, 0.5, 2.5);
airplaneGroup.add(vStab);
scene.add(airplaneGroup);
// Headlights (spotlight) setup
let headlights = null;
function updateHeadlights() {
// Check if player owns the headlights upgrade
const ownedUpgrades = JSON.parse(localStorage.getItem('ownedUpgrades')) || [];
if (ownedUpgrades.includes('headlights')) {
if (!headlights) {
headlights = new THREE.SpotLight(0xffffff, 2, 100, Math.PI / 8, 0.5, 1);
// Place at the front of the plane in world space (+X is front due to fuselage rotation)
headlights.position.set(2.5, 0, 0);
headlights.target.position.set(12, 0, 0);
airplaneGroup.add(headlights);
airplaneGroup.add(headlights.target);
}
// Always update position and direction to be at the front and point forward (+X in local space)
// Use localToWorld to get the correct world position for the front
const frontLocal = new THREE.Vector3(2.5, 0, 0);
const targetLocal = new THREE.Vector3(12, 0, 0);
const frontWorld = airplaneGroup.localToWorld(frontLocal.clone());
const targetWorld = airplaneGroup.localToWorld(targetLocal.clone());
// Remove from parent to set world position, then re-add to airplaneGroup
scene.add(headlights);
scene.add(headlights.target);
headlights.position.copy(frontWorld);
headlights.target.position.copy(targetWorld);
airplaneGroup.attach(headlights);
airplaneGroup.attach(headlights.target);
headlights.visible = true;
} else if (headlights) {
headlights.visible = false;
}
}
// Enemy airplane
const enemyGroup = new THREE.Group();
const enemyMaterial = new THREE.MeshPhongMaterial({
color: 0xff0000,
shininess: 150,
specular: 0xaaaaaa
});
const enemyFuselage = new THREE.Mesh(fuselageGeometry, enemyMaterial);
enemyFuselage.rotation.z = Math.PI / 2;
enemyGroup.add(enemyFuselage);
const enemyLeftWing = new THREE.Mesh(new THREE.BoxGeometry(6, 0.2, 1), new THREE.MeshPhongMaterial({ color: 0x800000 }));
enemyLeftWing.position.set(-1.5, 0, 0);
enemyGroup.add(enemyLeftWing);
const enemyRightWing = new THREE.Mesh(new THREE.BoxGeometry(6, 0.2, 1), new THREE.MeshPhongMaterial({ color: 0x800000 }));
enemyRightWing.position.set(1.5, 0, 0);
enemyGroup.add(enemyRightWing);
const enemyTail = new THREE.Mesh(tailGeometry, new THREE.MeshPhongMaterial({ color: 0x800000 }));
enemyTail.position.set(0, 0, 2.5);
enemyGroup.add(enemyTail);
const enemyVStab = new THREE.Mesh(vStabGeometry, new THREE.MeshPhongMaterial({ color: 0x800000 }));
enemyVStab.position.set(0, 0.5, 2.5);
enemyGroup.add(enemyVStab);
enemyGroup.position.set(20, 10, -20);
scene.add(enemyGroup);
// Camera setup
camera.position.set(0, 5, 15);
scene.add(camera);
// Flight dynamics
let velocity = new THREE.Vector3(0, 0, 0);
const acceleration = 0.2; // Adjusted for responsiveness
const gravity = -0.002;
let currency = parseInt(localStorage.getItem('currency')) || 0;
const ownedUpgrades = JSON.parse(localStorage.getItem('ownedUpgrades')) || [];
// Apply upgrades
let maxSpeed = 1.5; // Default speed
let armor = 1; // Default armor
let stealthMode = false;
if (ownedUpgrades.includes('speed')) maxSpeed += 0.5; // Increase speed
if (ownedUpgrades.includes('armor')) armor += 1; // Increase armor
if (ownedUpgrades.includes('stealth')) stealthMode = true; // Enable stealth mode
// Enhanced AI behavior
const enemyAcceleration = 0.05;
const enemyMaxSpeed = 1.2; // Slightly slower than the player
let enemyVelocity = new THREE.Vector3();
function updateEnemyAI() {
const directionToPlayer = airplaneGroup.position.clone().sub(enemyGroup.position).normalize();
const randomPerturbation = new THREE.Vector3(
(Math.random() - 0.5) * 0.1,
(Math.random() - 0.5) * 0.1,
(Math.random() - 0.5) * 0.1
);
const targetDirection = directionToPlayer.add(randomPerturbation).normalize();
const acceleration = targetDirection.multiplyScalar(enemyAcceleration);
enemyVelocity.add(acceleration).clampLength(0, enemyMaxSpeed);
enemyGroup.position.add(enemyVelocity.clone().multiplyScalar(0.1));
enemyGroup.lookAt(airplaneGroup.position);
}
// Bullets (player and enemy)
const bullets = [];
const enemyBullets = [];
const bulletSpeed = 2;
const bulletLifetime = 2;
let lastEnemyShot = 0;
// AI waypoints
const waypoints = [
new THREE.Vector3(20, 10, -20),
new THREE.Vector3(-20, 15, -40),
new THREE.Vector3(0, 20, 20),
new THREE.Vector3(40, 10, 0)
];
let currentWaypoint = 0;
// Keyboard controls
const keys = {};
document.addEventListener('keydown', (event) => {
keys[event.key] = true;
if (event.key === ' ' && !keys['spacePressed']) {
keys['spacePressed'] = true;
const bulletGeometry = new THREE.SphereGeometry(0.1, 8, 8);
const bulletMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
bullet.position.copy(airplaneGroup.position);
bullet.quaternion.copy(airplaneGroup.quaternion);
bullet.userData = {
velocity: new THREE.Vector3(0, 0, -bulletSpeed).applyQuaternion(airplaneGroup.quaternion),
time: performance.now() / 1000
};
scene.add(bullet);
bullets.push(bullet);
}
});
document.addEventListener('keyup', (event) => {
keys[event.key] = false;
if (event.key === ' ') keys['spacePressed'] = false;
});
// Terrain height
function getTerrainHeight(x, z) {
const scale = terrainSize / terrainSegments;
const gridX = Math.floor((x + terrainSize / 2) / scale);
const gridZ = Math.floor((z + terrainSize / 2) / scale);
if (gridX < 0 || gridX >= terrainSegments || gridZ < 0 || gridZ >= terrainSegments) return -50;
const index = (gridZ * (terrainSegments + 1) + gridX) * 3 + 2;
return vertices[index] - 50;
}
// Health bar state
let playerMaxHealth = 100;
let playerHealth = playerMaxHealth;
let enemyMaxHealth = 100;
let enemyHealth = enemyMaxHealth;
// --- ROUND SYSTEM STATE ---
let round = 1;
let planesToDestroy = 5;
let planesDestroyedThisRound = 0;
let roundEarnings = 0;
let inGame = true;
function updateFlightDynamics() {
// Player movement
let acc = new THREE.Vector3(0, 0, 0);
if (keys['w']) acc.z -= acceleration;
if (keys['s']) acc.z += acceleration;
if (keys['a']) acc.x -= acceleration;
if (keys['d']) acc.x += acceleration;
if (keys['ArrowUp']) acc.y += acceleration;
if (keys['ArrowDown']) acc.y -= acceleration;
acc.y += gravity;
velocity.add(acc);
velocity.clampLength(0, maxSpeed);
airplaneGroup.position.add(velocity.clone().multiplyScalar(0.1));
// Terrain collision
const terrainHeight = getTerrainHeight(airplaneGroup.position.x, airplaneGroup.position.z);
if (airplaneGroup.position.y < terrainHeight + 1) {
airplaneGroup.position.y = terrainHeight + 1;
velocity.y = Math.max(velocity.y, 0);
}
// Enemy AI
updateEnemyAI();
// Enemy firing
const currentTime = performance.now() / 1000;
if (currentTime - lastEnemyShot > 2) {
const bulletGeometry = new THREE.SphereGeometry(0.1, 8, 8);
const bulletMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
// --- FIX: Position the bullet at the front of the enemy airplane ---
// The enemyGroup's local +X axis is the front (because the fuselage is rotated z=PI/2)
// So we use a positive X offset in local space, then convert to world space
const frontOffset = new THREE.Vector3(2.5, 0, 0); // 2.5 units in +X (front)
const worldFront = enemyGroup.localToWorld(frontOffset.clone());
bullet.position.copy(worldFront);
// Predictive aiming: estimate where the player will be
const playerFuture = airplaneGroup.position.clone().add(
velocity.clone().normalize().multiplyScalar(2.5)
);
const directionToFuturePlayer = playerFuture.clone().sub(bullet.position).normalize();
bullet.userData = {
velocity: directionToFuturePlayer.multiplyScalar(bulletSpeed),
time: currentTime
};
scene.add(bullet);
enemyBullets.push(bullet);
lastEnemyShot = currentTime;
}
// Add smoke trail behind player
if (velocity.length() > 0.5 && Math.random() < 0.2) addSmokeTrail();
updateSmokeTrail();
// Player bullets and currency reward
for (let i = bullets.length - 1; i >= 0; i--) {
const bullet = bullets[i];
bullet.position.add(bullet.userData.velocity.clone().multiplyScalar(0.1));
if (bullet.position.distanceTo(enemyGroup.position) < 2) {
// Damage enemy
enemyHealth -= 50;
if (enemyHealth <= 0) {
planesDestroyedThisRound++;
roundEarnings += 50;
createExplosion(enemyGroup.position.clone());
triggerCameraShake();
scene.remove(bullet);
bullets.splice(i, 1);
enemyGroup.position.copy(waypoints[Math.floor(Math.random() * waypoints.length)]);
enemyHealth = enemyMaxHealth;
document.getElementById('missionText').textContent = "Enemy destroyed! New enemy incoming!";
setTimeout(() => {
document.getElementById('missionText').textContent = "Destroy the enemy plane!";
}, 2000);
// Check for round completion
if (planesDestroyedThisRound >= planesToDestroy) {
inGame = false;
showRoundCompleteDialog();
}
continue;
}
scene.remove(bullet);
bullets.splice(i, 1);
continue;
}
if (currentTime - bullet.userData.time > bulletLifetime) {
scene.remove(bullet);
bullets.splice(i, 1);
}
}
// Enemy bullets and player hit detection
for (let i = enemyBullets.length - 1; i >= 0; i--) {
const bullet = enemyBullets[i];
bullet.position.add(bullet.userData.velocity.clone().multiplyScalar(0.1));
if (bullet.position.distanceTo(airplaneGroup.position) < 2) {
if (armor > 0) {
armor--;
alert('Armor absorbed the hit!');
} else {
playerHealth -= 25;
if (playerHealth <= 0) {
inGame = false;
showDeathPaymentDialog();
break;
}
}
createExplosion(airplaneGroup.position.clone());
triggerCameraShake();
scene.remove(bullet);
enemyBullets.splice(i, 1);
continue;
}
if (currentTime - bullet.userData.time > bulletLifetime) {
scene.remove(bullet);
enemyBullets.splice(i, 1);
}
}
// Update headlights if owned
updateHeadlights();
// Update HUD
document.getElementById('currency').textContent = currency;
document.getElementById('speed').textContent = (velocity.length() * 100).toFixed(2);
const altitude = airplaneGroup.position.y.toFixed(2);
document.getElementById('altitude').textContent = altitude;
// Update health bar
document.getElementById('healthBar').style.width = (playerHealth / playerMaxHealth * 100) + "%";
document.getElementById('healthValue').textContent = playerHealth;
// Update minimap
updateMinimap();
// Update round reminder in HUD
document.getElementById('roundReminder').textContent =
`Round ${round}: Destroy ${planesToDestroy} planes (Remaining: ${planesToDestroy - planesDestroyedThisRound}).`;
// Update camera
const offset = new THREE.Vector3(0, 5, 15);
camera.position.copy(airplaneGroup.position).add(offset);
camera.lookAt(airplaneGroup.position);
// Visuals
updateCameraEffects();
}
// Mini-map rendering
function updateMinimap() {
const canvas = document.getElementById('minimap');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw terrain bounds
ctx.strokeStyle = "#fff";
ctx.lineWidth = 2;
ctx.strokeRect(10, 10, 100, 100);
// Player position (centered)
const px = (airplaneGroup.position.x / terrainSize) * 50 + 60;
const pz = (airplaneGroup.position.z / terrainSize) * 50 + 60;
ctx.fillStyle = "#00ff00";
ctx.beginPath();
ctx.arc(px, pz, 6, 0, 2 * Math.PI);
ctx.fill();
// Enemy position
const ex = (enemyGroup.position.x / terrainSize) * 50 + 60;
const ez = (enemyGroup.position.z / terrainSize) * 50 + 60;
ctx.fillStyle = "#ff0000";
ctx.beginPath();
ctx.arc(ex, ez, 6, 0, 2 * Math.PI);
ctx.fill();
// Optionally: draw waypoints or other objects
}
// Add death message overlay
function showDeathMessage() {
let msg = document.getElementById('deathMessage');
if (!msg) {
msg = document.createElement('div');
msg.id = 'deathMessage';
msg.style.position = 'fixed';
msg.style.top = '50%';
msg.style.left = '50%';
msg.style.transform = 'translate(-50%, -50%)';
msg.style.background = 'rgba(0,0,0,0.8)';
msg.style.color = '#fff';
msg.style.fontSize = '2rem';
msg.style.padding = '40px 60px';
msg.style.borderRadius = '16px';
msg.style.zIndex = 9999;
msg.style.textAlign = 'center';
msg.innerHTML = 'You have been shot down!';
document.body.appendChild(msg);
} else {
msg.style.display = 'block';
}
}
function hideDeathMessage() {
const msg = document.getElementById('deathMessage');
if (msg) msg.style.display = 'none';
}
// --- ROUND/DEATH DIALOGS ---
function showDeathPaymentDialog() {
// Overlay
let overlay = document.getElementById('deathPaymentOverlay');
if (!overlay) {
overlay = document.createElement('div');
overlay.id = 'deathPaymentOverlay';
overlay.style.position = 'fixed';
overlay.style.top = 0;
overlay.style.left = 0;
overlay.style.width = '100vw';
overlay.style.height = '100vh';
overlay.style.background = 'rgba(0,0,0,0.85)';
overlay.style.display = 'flex';
overlay.style.flexDirection = 'column';
overlay.style.alignItems = 'center';
overlay.style.justifyContent = 'center';
overlay.style.zIndex = 99999;
overlay.innerHTML = `
<div style="background:#222; color:#fff; padding:40px 30px; border-radius:16px; text-align:center;">
<h2>You have been shot down!</h2>
<p>Pay <b>500 coins</b> to continue this round?</p>
<button id="payToContinueBtn" style="margin:10px 20px; padding:10px 30px; font-size:1.2rem;">Pay & Continue</button>
<button id="giveUpBtn" style="margin:10px 20px; padding:10px 30px; font-size:1.2rem; background:#dc3545; color:#fff;">Give Up</button>
</div>
`;
document.body.appendChild(overlay);
} else {
overlay.style.display = 'flex';
}
document.getElementById('payToContinueBtn').onclick = function() {
if (currency >= 500) {
currency -= 500;
localStorage.setItem('currency', currency);
document.getElementById('currency').textContent = currency;
playerHealth = playerMaxHealth;
velocity.set(0, 0, 0);
airplaneGroup.position.set(0, 5, 15);
overlay.style.display = 'none';
inGame = true;
} else {
alert("Not enough coins! You can't continue.");
}
};
document.getElementById('giveUpBtn').onclick = function() {
overlay.innerHTML = `
<div style="background:#222; color:#fff; padding:40px 30px; border-radius:16px; text-align:center;">
<h2>Game Over</h2>
<p>You didn't have enough coins to continue. You lost your round earnings.</p>
<a href="/index.html" style="display:inline-block; margin-top:20px; padding:10px 30px; background:#007BFF; color:#fff; border-radius:8px; text-decoration:none; font-size:1.1rem;">Back to Homepage</a>
</div>
`;
};
}
function showRoundCompleteDialog() {
let overlay = document.getElementById('roundCompleteOverlay');
if (!overlay) {
overlay = document.createElement('div');
overlay.id = 'roundCompleteOverlay';
overlay.style.position = 'fixed';
overlay.style.top = 0;
overlay.style.left = 0;
overlay.style.width = '100vw';
overlay.style.height = '100vh';
overlay.style.background = 'rgba(0,0,0,0.85)';
overlay.style.display = 'flex';
overlay.style.flexDirection = 'column';
overlay.style.alignItems = 'center';
overlay.style.justifyContent = 'center';
overlay.style.zIndex = 99999;
document.body.appendChild(overlay);
}
overlay.innerHTML = `
<div style="background:#222; color:#fff; padding:40px 30px; border-radius:16px; text-align:center;">
<h2>Round Complete!</h2>
<p>You destroyed ${planesToDestroy} planes and earned <b>${roundEarnings} coins</b> this round.</p>
<button id="nextRoundBtn" style="margin:10px 20px; padding:10px 30px; font-size:1.2rem;">Next Round</button>
<button id="toHomeBtn" style="margin:10px 20px; padding:10px 30px; font-size:1.2rem; background:#007BFF; color:#fff;">Back to Homepage</button>
</div>
`;
document.getElementById('nextRoundBtn').onclick = function() {
// Add round earnings to currency
currency += roundEarnings;
localStorage.setItem('currency', currency);
document.getElementById('currency').textContent = currency;
round++;
planesToDestroy++;
planesDestroyedThisRound = 0;
roundEarnings = 0;
playerHealth = playerMaxHealth;
velocity.set(0, 0, 0);
airplaneGroup.position.set(0, 5, 15);
overlay.style.display = 'none';
inGame = true;
// Ensure animation loop continues
animate();
};
document.getElementById('toHomeBtn').onclick = function() {
// Add round earnings to currency
currency += roundEarnings;
localStorage.setItem('currency', currency);
window.location.href = "/index.html";
};
}
// Animation loop
let lastTime = performance.now() / 1000;
function animate() {
requestAnimationFrame(animate);
const now = performance.now() / 1000;
const delta = now - lastTime;
lastTime = now;
if (inGame) {
updateSkyAndWeather(delta);
updateFlightDynamics();
}
renderer.render(scene, camera);
}
animate();
// Window resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Realistic Airplane Models (future):
// Replace the createAirplane code with model loading using THREE.GLTFLoader or similar.
// Example:
// const loader = new THREE.GLTFLoader();
// loader.load('path/to/model.glb', gltf => { scene.add(gltf.scene); });
</script>
</body>
</html>