Repository navigation
Expand file tree
/
Copy pathgame.js
More file actions
1933 lines (1578 loc) · 68.6 KB
/
Copy pathgame.js
File metadata and controls
1933 lines (1578 loc) · 68.6 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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
class CubeCollectorGame {
constructor() {
this.scene = null;
this.camera = null;
this.renderer = null;
this.player = null;
this.collectibles = [];
this.enemies = [];
this.shooterEnemies = [];
this.bomberEnemies = [];
this.bullets = [];
this.enemyBullets = [];
this.bombs = [];
this.score = 0;
this.keys = {};
this.mouse = { x: 0, y: 0 };
this.gameSpeed = 0.1;
this.gameOver = false;
this.autoShoot = false; // Auto-shooting state
this.autoShootForward = false; // Auto-shooting forward state
this.lives = 3;
this.lastShotTime = 0;
this.shotCooldown = 200; // milliseconds
this.playerSize = 1; // Starting size
this.powerLevel = 1; // Power level based on cubes collected
this.cubesEaten = 0; // Track total cubes eaten
this.audioContext = null;
this.sounds = {};
this.init();
this.initAudio();
this.setupControls();
this.updateLives();
this.updatePowerDisplay();
this.gameLoop();
}
initAudio() {
try {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Create master gain node for volume control
this.masterGain = this.audioContext.createGain();
this.masterGain.gain.value = 0.3; // Master volume at 30%
this.masterGain.connect(this.audioContext.destination);
console.log('Audio system initialized');
} catch (error) {
console.warn('Audio not supported:', error);
}
}
// Generic sound synthesis function
playSound(frequency, duration, type = 'sine', volume = 0.1, fadeOut = true) {
if (!this.audioContext) return;
try {
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.masterGain);
oscillator.frequency.setValueAtTime(frequency, this.audioContext.currentTime);
oscillator.type = type;
gainNode.gain.setValueAtTime(volume, this.audioContext.currentTime);
if (fadeOut) {
gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + duration);
}
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime + duration);
} catch (error) {
console.warn('Error playing sound:', error);
}
}
// Shooting sound effect
playShootSound() {
if (!this.audioContext) return;
try {
// Laser-like shooting sound
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.masterGain);
// Frequency sweep from high to low
oscillator.frequency.setValueAtTime(800, this.audioContext.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(200, this.audioContext.currentTime + 0.1);
oscillator.type = 'sawtooth';
gainNode.gain.setValueAtTime(0.15, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + 0.1);
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime + 0.1);
} catch (error) {
console.warn('Error playing shoot sound:', error);
}
}
// Collection sound effect
playCollectSound() {
if (!this.audioContext) return;
try {
// Pleasant collection chime
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.masterGain);
// Frequency sweep upward
oscillator.frequency.setValueAtTime(440, this.audioContext.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(880, this.audioContext.currentTime + 0.3);
oscillator.type = 'sine';
gainNode.gain.setValueAtTime(0.2, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + 0.3);
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime + 0.3);
} catch (error) {
console.warn('Error playing collect sound:', error);
}
}
// Explosion sound effect
playExplosionSound() {
if (!this.audioContext) return;
try {
// Create noise-based explosion
const bufferSize = this.audioContext.sampleRate * 0.5; // 0.5 seconds
const buffer = this.audioContext.createBuffer(1, bufferSize, this.audioContext.sampleRate);
const data = buffer.getChannelData(0);
// Generate white noise
for (let i = 0; i < bufferSize; i++) {
data[i] = Math.random() * 2 - 1;
}
const source = this.audioContext.createBufferSource();
const gainNode = this.audioContext.createGain();
const filter = this.audioContext.createBiquadFilter();
source.buffer = buffer;
source.connect(filter);
filter.connect(gainNode);
gainNode.connect(this.masterGain);
filter.type = 'lowpass';
filter.frequency.setValueAtTime(1000, this.audioContext.currentTime);
filter.frequency.exponentialRampToValueAtTime(100, this.audioContext.currentTime + 0.5);
gainNode.gain.setValueAtTime(0.3, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + 0.5);
source.start(this.audioContext.currentTime);
} catch (error) {
console.warn('Error playing explosion sound:', error);
}
}
// Damage/hit sound effect
playDamageSound() {
if (!this.audioContext) return;
try {
// Sharp, unpleasant damage sound
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.masterGain);
oscillator.frequency.setValueAtTime(150, this.audioContext.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(50, this.audioContext.currentTime + 0.2);
oscillator.type = 'square';
gainNode.gain.setValueAtTime(0.25, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + 0.2);
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime + 0.2);
} catch (error) {
console.warn('Error playing damage sound:', error);
}
}
// Power up sound effect
playPowerUpSound() {
if (!this.audioContext) return;
try {
// Ascending power-up chime
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.masterGain);
oscillator.frequency.setValueAtTime(220, this.audioContext.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(660, this.audioContext.currentTime + 0.4);
oscillator.type = 'triangle';
gainNode.gain.setValueAtTime(0.15, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + 0.4);
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime + 0.4);
} catch (error) {
console.warn('Error playing power up sound:', error);
}
}
// Enemy shooting sound effect
playEnemyShootSound() {
if (!this.audioContext) return;
try {
// Different sound for enemy shots
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.masterGain);
oscillator.frequency.setValueAtTime(300, this.audioContext.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(150, this.audioContext.currentTime + 0.15);
oscillator.type = 'square';
gainNode.gain.setValueAtTime(0.1, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + 0.15);
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime + 0.15);
} catch (error) {
console.warn('Error playing enemy shoot sound:', error);
}
}
init() {
// Create scene
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x001122);
// Setup camera
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
this.camera.position.set(0, 10, 10);
this.camera.lookAt(0, 0, 0);
// Setup renderer
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.getElementById('gameArea').appendChild(this.renderer.domElement);
// Setup lighting
this.setupLighting();
// Create ground
this.createGround();
// Create player
this.createPlayer();
// Create collectibles
this.createCollectibles();
// Create enemies
this.createEnemies();
this.createShooterEnemies();
this.createBomberEnemies();
// Handle window resize
window.addEventListener('resize', () => this.onWindowResize());
}
setupLighting() {
// Ambient light
const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
this.scene.add(ambientLight);
// Directional light
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(10, 10, 5);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
directionalLight.shadow.camera.near = 0.5;
directionalLight.shadow.camera.far = 500;
this.scene.add(directionalLight);
// Point light for atmosphere
const pointLight = new THREE.PointLight(0x00ffff, 0.5, 50);
pointLight.position.set(0, 10, 0);
this.scene.add(pointLight);
}
createGround() {
const fieldSize = 75; // 50 * 1.5 = 75
const groundGeometry = new THREE.PlaneGeometry(fieldSize, fieldSize);
// Create grass texture
const canvas = document.createElement('canvas');
canvas.width = 512;
canvas.height = 512;
const context = canvas.getContext('2d');
// Create grass texture pattern
this.createGrassTexture(context, canvas.width, canvas.height);
const grassTexture = new THREE.CanvasTexture(canvas);
grassTexture.wrapS = THREE.RepeatWrapping;
grassTexture.wrapT = THREE.RepeatWrapping;
grassTexture.repeat.set(8, 8); // Repeat texture across the field
const groundMaterial = new THREE.MeshLambertMaterial({
map: grassTexture,
color: 0x88aa66, // Tint the grass texture slightly green
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
this.scene.add(ground);
// Add grid helper for the larger field
const gridHelper = new THREE.GridHelper(fieldSize, fieldSize, 0x555533, 0x444422);
gridHelper.material.opacity = 0.3;
gridHelper.material.transparent = true;
this.scene.add(gridHelper);
}
createGrassTexture(context, width, height) {
// Fill with base grass color
context.fillStyle = '#2d5016';
context.fillRect(0, 0, width, height);
// Add grass blade patterns
for (let i = 0; i < 1000; i++) {
const x = Math.random() * width;
const y = Math.random() * height;
const grassShade = Math.random() * 0.3 + 0.4;
context.fillStyle = `hsl(${80 + Math.random() * 40}, ${60 + Math.random() * 30}%, ${grassShade * 100}%)`;
// Draw small grass blade
context.fillRect(x, y, 1 + Math.random() * 2, 2 + Math.random() * 3);
}
// Add some darker spots for dirt patches
for (let i = 0; i < 50; i++) {
const x = Math.random() * width;
const y = Math.random() * height;
const size = 3 + Math.random() * 8;
context.fillStyle = `hsl(${30 + Math.random() * 20}, ${40 + Math.random() * 20}%, ${20 + Math.random() * 15}%)`;
context.beginPath();
context.arc(x, y, size, 0, Math.PI * 2);
context.fill();
}
}
createPlayer() {
const geometry = new THREE.BoxGeometry(this.playerSize, this.playerSize, this.playerSize);
const material = new THREE.MeshPhongMaterial({
color: 0x00ff88,
shininess: 100,
emissive: 0x002200
});
this.player = new THREE.Mesh(geometry, material);
this.player.position.set(0, this.playerSize / 2, 0);
this.player.castShadow = true;
this.scene.add(this.player);
}
updatePlayerSize() {
// Store current position before removing old player
const currentPosition = {
x: this.player.position.x,
y: this.player.position.y,
z: this.player.position.z
};
// Remove old player
this.scene.remove(this.player);
// Calculate new size based on cubes eaten (grows by 0.1 per cube, max 3x)
this.playerSize = Math.min(1 + (this.cubesEaten * 0.1), 3);
this.powerLevel = Math.floor(this.cubesEaten / 3) + 1; // Power level every 3 cubes
// Create new player with updated size
const geometry = new THREE.BoxGeometry(this.playerSize, this.playerSize, this.playerSize);
const material = new THREE.MeshPhongMaterial({
color: this.getPlayerColor(),
shininess: 100,
emissive: this.getPlayerEmissive()
});
this.player = new THREE.Mesh(geometry, material);
// Preserve the exact position, just adjust Y for the new size
this.player.position.set(currentPosition.x, this.playerSize / 2, currentPosition.z);
this.player.castShadow = true;
this.scene.add(this.player);
// Update shooting cooldown based on player size (faster shooting as you grow)
this.shotCooldown = Math.max(30, 200 - (this.playerSize * 50));
}
getPlayerColor() {
// Color evolves from green to bright green to cyan based on size
const hue = Math.max(0.15, 0.33 - (this.playerSize * 0.06)); // Green shifting to cyan-yellow
const saturation = Math.min(1, 0.8 + (this.playerSize * 0.08));
const lightness = Math.min(0.8, 0.45 + (this.playerSize * 0.08));
return new THREE.Color().setHSL(hue, saturation, lightness);
}
getPlayerEmissive() {
// Stronger glow as size increases
const intensity = Math.min(0.4, this.playerSize * 0.08);
const hue = Math.max(0.15, 0.33 - (this.playerSize * 0.06));
return new THREE.Color().setHSL(hue, 1, intensity);
}
createCollectibles() {
for (let i = 0; i < 15; i++) {
const geometry = new THREE.SphereGeometry(0.3, 12, 8); // Sphere instead of cube
const hue = Math.random();
const material = new THREE.MeshPhongMaterial({
color: new THREE.Color().setHSL(hue, 1, 0.6),
shininess: 150,
emissive: new THREE.Color().setHSL(hue, 0.8, 0.15)
});
const collectible = new THREE.Mesh(geometry, material);
// Random position within bounds (expanded field)
collectible.position.set(
(Math.random() - 0.5) * 60, // 40 * 1.5 = 60
0.3, // Slightly higher for spheres
(Math.random() - 0.5) * 60
);
collectible.castShadow = true;
collectible.userData = {
originalY: collectible.position.y,
floatSpeed: Math.random() * 0.02 + 0.01,
rotationSpeed: Math.random() * 0.05 + 0.02,
pulseSpeed: Math.random() * 0.03 + 0.02 // Add pulsing effect
};
this.collectibles.push(collectible);
this.scene.add(collectible);
}
}
createBomberEnemies() {
for (let i = 0; i < 2; i++) { // Start with 2 bomber enemies
this.spawnNewBomberEnemy();
}
}
spawnNewBomberEnemy() {
const geometry = new THREE.BoxGeometry(1.5, 0.8, 1.5); // Larger, flatter shape
const material = new THREE.MeshPhongMaterial({
color: 0x8800aa, // Purple color for distinction
emissive: 0x220055,
shininess: 30
});
const bomberEnemy = new THREE.Mesh(geometry, material);
// Position higher up (flying)
bomberEnemy.position.set(
(Math.random() - 0.5) * 60,
3.5, // Flying height
(Math.random() - 0.5) * 60
);
bomberEnemy.castShadow = true;
bomberEnemy.receiveShadow = true;
// Add bomber-specific properties
bomberEnemy.userData = {
speed: 0.025 + Math.random() * 0.015, // Faster, more aggressive
lastBombTime: Date.now() + Math.random() * 2000, // Random initial delay
bombCooldown: 3000 + Math.random() * 1500, // 3-4.5 seconds between bombs
type: 'bomber',
detectionRange: 15, // How far they can detect player
bombingRange: 8, // How close they get before bombing
chaseMode: false // Whether actively chasing player
};
// Create visual indicator (rotating ring)
this.createBomberIndicator(bomberEnemy);
this.bomberEnemies.push(bomberEnemy);
this.scene.add(bomberEnemy);
}
createBomberIndicator(bomberEnemy) {
const indicatorGeometry = new THREE.TorusGeometry(1.2, 0.05, 6, 12);
const indicatorMaterial = new THREE.MeshPhongMaterial({
color: 0xffaa00, // Orange warning ring
emissive: 0x441100,
transparent: true,
opacity: 0.8
});
const indicator = new THREE.Mesh(indicatorGeometry, indicatorMaterial);
indicator.position.set(0, -0.5, 0); // Below the bomber
indicator.rotation.x = Math.PI / 2; // Horizontal ring
bomberEnemy.add(indicator);
bomberEnemy.userData.indicator = indicator;
}
updateBomberEnemies() {
if (this.gameOver) return;
this.bomberEnemies.forEach((bomberEnemy, index) => {
const currentTime = Date.now();
// Calculate distance to player
const distanceToPlayer = bomberEnemy.position.distanceTo(this.player.position);
// Check if player is in detection range
if (distanceToPlayer <= bomberEnemy.userData.detectionRange) {
bomberEnemy.userData.chaseMode = true;
} else if (distanceToPlayer > bomberEnemy.userData.detectionRange * 1.5) {
bomberEnemy.userData.chaseMode = false;
}
if (bomberEnemy.userData.chaseMode) {
// Aggressive chase mode - fly toward player
const direction = new THREE.Vector3()
.subVectors(this.player.position, bomberEnemy.position)
.normalize();
// Move toward player but maintain flying height
bomberEnemy.position.x += direction.x * bomberEnemy.userData.speed;
bomberEnemy.position.z += direction.z * bomberEnemy.userData.speed;
// Face the player while chasing
bomberEnemy.lookAt(this.player.position.x, bomberEnemy.position.y, this.player.position.z);
// Change indicator color to red when chasing
if (bomberEnemy.userData.indicator) {
bomberEnemy.userData.indicator.material.color.setHex(0xff0000);
bomberEnemy.userData.indicator.rotation.z += 0.1; // Faster rotation when aggressive
}
} else {
// Patrol mode - slower circular movement
const time = currentTime * 0.001;
const patrolRadius = 25;
const angle = time * bomberEnemy.userData.speed * 0.3;
const targetX = Math.cos(angle) * patrolRadius;
const targetZ = Math.sin(angle) * patrolRadius;
bomberEnemy.position.x += (targetX - bomberEnemy.position.x) * 0.01;
bomberEnemy.position.z += (targetZ - bomberEnemy.position.z) * 0.01;
// Slow rotation when patrolling
bomberEnemy.rotation.y += 0.01;
// Normal indicator color when patrolling
if (bomberEnemy.userData.indicator) {
bomberEnemy.userData.indicator.material.color.setHex(0xffaa00);
bomberEnemy.userData.indicator.rotation.z += 0.03;
}
}
// Keep within bounds
bomberEnemy.position.x = Math.max(-35, Math.min(35, bomberEnemy.position.x));
bomberEnemy.position.z = Math.max(-35, Math.min(35, bomberEnemy.position.z));
// Strategic bombing - only bomb when close to player and in chase mode
const shouldBomb = bomberEnemy.userData.chaseMode &&
distanceToPlayer <= bomberEnemy.userData.bombingRange &&
currentTime - bomberEnemy.userData.lastBombTime > bomberEnemy.userData.bombCooldown;
if (shouldBomb) {
this.dropBomb(bomberEnemy);
bomberEnemy.userData.lastBombTime = currentTime;
}
});
}
dropBomb(bomberEnemy) {
const bombGeometry = new THREE.SphereGeometry(0.2, 8, 6);
const bombMaterial = new THREE.MeshPhongMaterial({
color: 0xff4400,
emissive: 0x330000,
shininess: 100
});
const bomb = new THREE.Mesh(bombGeometry, bombMaterial);
bomb.position.copy(bomberEnemy.position);
bomb.position.y = bomberEnemy.position.y - 0.5; // Drop from bottom of bomber
bomb.castShadow = true;
// Add bomb properties
bomb.userData = {
velocity: new THREE.Vector3(0, 0, 0), // Start with no velocity
gravity: -0.02, // Gravity acceleration
exploded: false,
fuseTime: 2000, // 2 seconds fuse after hitting ground
dropTime: Date.now(),
blastRadius: 4.0 // Explosion radius
};
this.bombs.push(bomb);
this.scene.add(bomb);
// Play bomb drop sound
this.playBombDropSound();
console.log('Bomb dropped!');
}
updateBombs() {
if (this.gameOver) return;
for (let i = this.bombs.length - 1; i >= 0; i--) {
const bomb = this.bombs[i];
const currentTime = Date.now();
if (bomb.userData.exploded) continue;
// Apply gravity if not on ground
if (bomb.position.y > 0.2) {
bomb.userData.velocity.y += bomb.userData.gravity;
bomb.position.add(bomb.userData.velocity);
// Rotation while falling
bomb.rotation.x += 0.1;
bomb.rotation.z += 0.1;
} else {
// Bomb hit ground
bomb.position.y = 0.2;
bomb.userData.velocity.y = 0;
// Start fuse timer if just hit ground
if (!bomb.userData.fuseStarted) {
bomb.userData.fuseStarted = true;
bomb.userData.fuseStartTime = currentTime;
// Create warning indicator
this.createBombWarning(bomb);
}
// Check if fuse expired
if (currentTime - bomb.userData.fuseStartTime > bomb.userData.fuseTime) {
this.explodeBomb(i);
} else {
// Fuse effect - pulsing red
const pulseIntensity = Math.sin((currentTime - bomb.userData.fuseStartTime) * 0.01) * 0.5 + 0.5;
bomb.material.emissive.setRGB(0.3 + pulseIntensity * 0.7, 0, 0);
}
}
}
}
createBombWarning(bomb) {
const warningGeometry = new THREE.RingGeometry(2, 4, 16);
const warningMaterial = new THREE.MeshBasicMaterial({
color: 0xff0000,
transparent: true,
opacity: 0.3,
side: THREE.DoubleSide
});
const warning = new THREE.Mesh(warningGeometry, warningMaterial);
warning.position.copy(bomb.position);
warning.position.y = 0.1;
warning.rotation.x = -Math.PI / 2;
bomb.userData.warning = warning;
this.scene.add(warning);
}
explodeBomb(bombIndex) {
const bomb = this.bombs[bombIndex];
const explosionCenter = bomb.position.clone();
// Remove warning indicator
if (bomb.userData.warning) {
this.scene.remove(bomb.userData.warning);
}
// Check if player is in blast radius
const distanceToPlayer = this.player.position.distanceTo(explosionCenter);
if (distanceToPlayer <= bomb.userData.blastRadius) {
// Player caught in explosion
this.playDamageSound();
this.handlePlayerCaught();
}
// Create explosion effect
this.createBombExplosion(explosionCenter);
// Play explosion sound
this.playExplosionSound();
// Remove bomb
this.scene.remove(bomb);
this.bombs.splice(bombIndex, 1);
console.log('Bomb exploded!');
}
createBombExplosion(position) {
// Create multiple explosion particles
for (let i = 0; i < 30; i++) {
const particleGeometry = new THREE.SphereGeometry(0.1 + Math.random() * 0.2, 4, 4);
const particleMaterial = new THREE.MeshBasicMaterial({
color: new THREE.Color().setHSL(0.1, 1, 0.5 + Math.random() * 0.5),
transparent: true,
opacity: 1
});
const particle = new THREE.Mesh(particleGeometry, particleMaterial);
particle.position.copy(position);
particle.position.y += 0.5;
// Random velocity
const velocity = new THREE.Vector3(
(Math.random() - 0.5) * 0.3,
Math.random() * 0.2,
(Math.random() - 0.5) * 0.3
);
particle.userData = {
velocity: velocity,
life: 1.0,
decay: 0.02 + Math.random() * 0.02
};
this.scene.add(particle);
// Animate and remove particle
const animateParticle = () => {
particle.position.add(particle.userData.velocity);
particle.userData.velocity.y -= 0.01; // Gravity
particle.userData.life -= particle.userData.decay;
particle.material.opacity = particle.userData.life;
if (particle.userData.life > 0) {
requestAnimationFrame(animateParticle);
} else {
this.scene.remove(particle);
}
};
animateParticle();
}
// Create blast wave ring
const blastGeometry = new THREE.RingGeometry(0.5, 4, 16);
const blastMaterial = new THREE.MeshBasicMaterial({
color: 0xff6600,
transparent: true,
opacity: 0.8,
side: THREE.DoubleSide
});
const blastWave = new THREE.Mesh(blastGeometry, blastMaterial);
blastWave.position.copy(position);
blastWave.position.y = 0.1;
blastWave.rotation.x = -Math.PI / 2;
this.scene.add(blastWave);
// Animate blast wave
let scale = 1;
const animateBlast = () => {
scale += 0.1;
blastWave.scale.setScalar(scale);
blastWave.material.opacity *= 0.9;
if (blastWave.material.opacity > 0.01) {
requestAnimationFrame(animateBlast);
} else {
this.scene.remove(blastWave);
}
};
animateBlast();
}
updateAutoShooting() {
if (this.gameOver) return;
const currentTime = Date.now();
// Check if enough time has passed since last shot
if (currentTime - this.lastShotTime >= this.shotCooldown) {
// Auto-shoot towards mouse if mouse button held
if (this.autoShoot) {
this.shoot();
}
// Auto-shoot forward if spacebar held
else if (this.autoShootForward) {
this.shootForward();
}
}
}
// Bomb drop sound effect
playBombDropSound() {
if (!this.audioContext) return;
try {
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.masterGain);
// Falling whistle sound
oscillator.frequency.setValueAtTime(600, this.audioContext.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(200, this.audioContext.currentTime + 1.0);
oscillator.type = 'sine';
gainNode.gain.setValueAtTime(0.1, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + 1.0);
oscillator.start(this.audioContext.currentTime);
oscillator.stop(this.audioContext.currentTime + 1.0);
} catch (error) {
console.warn('Error playing bomb drop sound:', error);
}
}
createEnemies() {
for (let i = 0; i < 5; i++) {
const geometry = new THREE.BoxGeometry(0.8, 0.8, 0.8);
const material = new THREE.MeshPhongMaterial({
color: 0xff0040,
shininess: 100,
emissive: 0x440011
});
const enemy = new THREE.Mesh(geometry, material);
// Random position within bounds, but away from player
let position;
do {
position = {
x: (Math.random() - 0.5) * 60, // Expanded field
y: 0.4,
z: (Math.random() - 0.5) * 60
};
} while (
Math.abs(position.x) < 5 && Math.abs(position.z) < 5
);
enemy.position.set(position.x, position.y, position.z);
enemy.castShadow = true;
enemy.userData = {
originalY: enemy.position.y,
floatSpeed: Math.random() * 0.015 + 0.01,
speed: Math.random() * 0.02 + 0.03,
lastDirection: new THREE.Vector3()
};
this.enemies.push(enemy);
this.scene.add(enemy);
}
}
createShooterEnemies() {
for (let i = 0; i < 3; i++) {
const geometry = new THREE.BoxGeometry(1.0, 1.0, 1.0);
const material = new THREE.MeshPhongMaterial({
color: 0xff8800,
shininess: 100,
emissive: 0x441100
});
const shooterEnemy = new THREE.Mesh(geometry, material);
// Random position within bounds, but away from player
let position;
do {
position = {
x: (Math.random() - 0.5) * 60, // Expanded field
y: 0.5,
z: (Math.random() - 0.5) * 60
};
} while (
Math.abs(position.x) < 8 && Math.abs(position.z) < 8
);
shooterEnemy.position.set(position.x, position.y, position.z);
shooterEnemy.castShadow = true;
shooterEnemy.userData = {
originalY: shooterEnemy.position.y,
floatSpeed: Math.random() * 0.01 + 0.005,
speed: Math.random() * 0.015 + 0.02, // Slower than red enemies
lastShotTime: 0,
shootCooldown: 2000 + Math.random() * 1000, // 2-3 second cooldown
detectionRange: 12,
shootingRange: 10
};
// Add visual indicator - rotating ring around the enemy
this.createShooterIndicator(shooterEnemy);
this.shooterEnemies.push(shooterEnemy);
this.scene.add(shooterEnemy);
}
}
createShooterIndicator(shooterEnemy) {
const ringGeometry = new THREE.TorusGeometry(0.8, 0.1, 8, 16);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0xffff00,
transparent: true,
opacity: 0.8
});
const ring = new THREE.Mesh(ringGeometry, ringMaterial);
ring.position.set(0, 0.8, 0);
ring.userData = { rotationSpeed: 0.05 };
shooterEnemy.add(ring); // Attach to the enemy
shooterEnemy.userData.indicator = ring;
}
setupControls() {
document.addEventListener('keydown', (event) => {
this.keys[event.code] = true;
});
document.addEventListener('keyup', (event) => {
this.keys[event.code] = false;
// Handle spacebar auto-shooting
if (event.code === 'Space') {
this.autoShootForward = false;
}
});
// Mouse controls for shooting
document.addEventListener('mousemove', (event) => {
this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
});
// Mouse button down/up for automatic shooting
document.addEventListener('mousedown', (event) => {
// Resume audio context on user interaction (required by browsers)
if (this.audioContext && this.audioContext.state === 'suspended') {
this.audioContext.resume();
}
if (!this.gameOver && event.button === 0) { // Left mouse button
this.autoShoot = true;
}
});
document.addEventListener('mouseup', (event) => {
if (event.button === 0) { // Left mouse button
this.autoShoot = false;
}
});
// Prevent context menu on right click
document.addEventListener('contextmenu', (event) => {
event.preventDefault();
});
// Stop auto-shooting if mouse leaves the window (prevents stuck shooting)
document.addEventListener('mouseleave', () => {
this.autoShoot = false;
});
// Stop auto-shooting if focus is lost (prevents stuck shooting)
window.addEventListener('blur', () => {
this.autoShoot = false;
this.autoShootForward = false;
});
// Direct event listener for Shift+R restart (more reliable)
document.addEventListener('keydown', (event) => {
if (event.code === 'KeyR' && event.shiftKey && this.gameOver) {
event.preventDefault();
this.restartGame();
}
});
// Space bar for automatic forward shooting - consolidated into main key handler