-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2114 lines (1834 loc) · 87.4 KB
/
script.js
File metadata and controls
2114 lines (1834 loc) · 87.4 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
import * as THREE from './js/three.module.js'
import { MarchingCubes } from './js/MarchingCubes.js'
// --- 1. 核心参数 ---
const RES = 60;
const WORLD_SIZE = 60;
let BRUSH_RADIUS = 2.0;
let EDIT_STRENGTH = 5.0;
const MOVE_SPEED = 0.3;
const LOOK_SENSITIVITY = 0.002;
let scene, camera, renderer, clock, hitMarker, planetCore;
let coreShieldMesh;
let effects = [];
let globalSkybox;
// --- [测试模式变量] ---
let isTestMode = false;
let orbitRadius = 20; // 改为20,更靠近飞船
let testViewOffset = { x: 0, y: 0 };
let playerShip;
let playerHealth = 100;
let shipLight;
// --- 游戏阶段变量 ---
let isPhaseTwo = false;
let isVictory = false;
let coreActivated = false; // 核心是否已激活特效
let coreOutline; // 核心白色包边
let coreGlowTime = 0; // 核心闪烁时间
let isDead = false; // 标记玩家是否已经死亡,防止重复触发
let gameStartTime = 0; // 新增:游戏开始时间
// --- 能量系统变量 ---
let shipEnergy = 50.0;
const MAX_ENERGY = 100.0;
const ENERGY_COST = 10.0; // 破坏弹能量消耗从20降低到10
// --- 移速等级系统 ---
let speedLevel = 0; // 当前移速等级 0-3
const SPEED_MULTIPLIERS = [1.0, 1.3, 1.6, 2.0]; // 各等级速度倍率
// --- 碎片累积系统 ---
let goldAccumulator = 0; // 黄金破坏累积值
let crystalAccumulator = 0; // 水晶破坏累积值
const GOLD_THRESHOLD = 0.5; // 累积1.0才产生1个黄金奖励碎片
const CRYSTAL_THRESHOLD = 0.5; // 累积1.0才产生1个水晶奖励碎片
// --- 武器过热系统 ---
let weaponHeat = 0; // 当前热量 0-100
const MAX_HEAT = 100;
const HEAT_PER_SHOT = 15; // 每发常规弹增加的热量,从20降低到15,过热更慢
const COOLING_RATE = 0.3; // 每帧冷却速度,从0.5降低到0.3,降温更慢
const OVERHEAT_THRESHOLD = 100; // 过热阈值
let isOverheated = false; // 是否过热
let lastFireTime = 0; // 上次发射时间
const FIRE_COOLDOWN = 150; // 常规弹射击间隔(毫秒),从100增加到150
// 物理速度
let localPitchVel = 0;
let localYawVel = 0;
const ORBIT_FRICTION = 0.92;
// 固定参数
const ORBIT_ACCEL_HIGH = 0.0001;
const ZOOM_ACCEL_HIGH = 0.008;
const ORBIT_ACCEL_LOW = 0.00004;
const ZOOM_ACCEL_LOW = 0.005;
// 第一人称参数
let fpsMoveVel = new THREE.Vector3();
let localZoomVel = 0;
const FPS_ACCEL = 0.02;
const FPS_FRICTION = 0.90;
// --- 模式定义 ---
const matNames = ["石材", "黄金", "水晶", "铁矿"];
const MAT_HARDNESS = [1.0, 0.1, 0.1, 2.0]; // 黄金和水晶硬度都是0.1(极低),石材3.0,铁矿8.0最高
const yellowTurretConfig = { name: "基础炮台(黄)", isTurret: true, type: 'basic', color: 0xffaa00 };
const redTurretConfig = { name: "标准炮台(红)", isTurret: true, type: 'standard', color: 0xaaaaaa };
const blueTurretConfig = { name: "追踪炮台(蓝)", isTurret: true, type: 'tracking', color: 0x004488 };
// --- 武器配置 ---
const weaponConfigs = [
{ name: "Standard Shot", radius: 3.0, strength: 0.05, color: 0xffaa00, isWeapon: true, pCount: 40, dCount: 12, minS: 0.05, maxS: 0.1, isHeavy: false, size: 0.1, directDamage: 5, areaDamage: 0 },
{ name: "Heavy Shot", radius: 4.5, strength: 0.5, color: 0xff0000, isWeapon: true, pCount: 200, dCount: 30, minS: 0.05, maxS: 0.1, isHeavy: true, size: 0.1, directDamage: 50, areaDamage: 20 }
];
const allModes = [...matNames, yellowTurretConfig, redTurretConfig, blueTurretConfig, ...weaponConfigs];
let currentModeIndex = 0;
const TOTAL_MODES = allModes.length;
const WEAPON_START_INDEX = matNames.length + 3;
let bullets = [];
let enemyBullets = [];
let particleGroups = [];
let rockDebris = [];
let turrets = []; // 外部炮台
let innerTurrets = []; // 内部核心炮台
// 保存测试模式开始时的状态快照
let testModeSnapshot = {
voxelFields: [], // 保存体素场数据
turrets: [], // 保存外部炮台
innerTurrets: [], // 保存内部炮台
cameraPosition: null, // 保存相机位置
orbitRadius: 60 // 保存轨道半径
};
// 材质定义
const turretMatYellow = new THREE.MeshStandardMaterial({
color: 0xffaa00, metalness: 0.7, roughness: 0.3, envMapIntensity: 1.0
});
const turretMatRed = new THREE.MeshStandardMaterial({
color: 0xaaaaaa, metalness: 1.0, roughness: 0.1, envMapIntensity: 1.0
});
const turretMatBlue = new THREE.MeshStandardMaterial({
color: 0x004488, metalness: 0.8, roughness: 0.2, envMapIntensity: 1.5
});
const shieldMat = new THREE.MeshBasicMaterial({
color: 0x0088ff, transparent: true, opacity: 0.3, side: THREE.DoubleSide
});
const coreShieldMat = new THREE.MeshBasicMaterial({ // 核心大护盾材质
color: 0xff00ff, transparent: true, opacity: 0.15, side: THREE.DoubleSide, wireframe: false, depthWrite: false
});
const laserMat = new THREE.LineBasicMaterial({
color: 0xff0000, transparent: true, opacity: 0.6, linewidth: 2
});
const outlineMat = new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.BackSide }); // 统一白色包边
const rewardOutlineMat = new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.BackSide }); // 奖励矿物白色包边
const coreOutlineMatBlue = new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.BackSide }); // 核心白色包边
const shipOutlineMat = new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.BackSide }); // 飞船白色包边
const enemyBulletMat = new THREE.MeshStandardMaterial({
color: 0x883322, emissive: 0x331100, metalness: 0.5, roughness: 0.1,
envMapIntensity: 0.3, flatShading: false, transparent: true, opacity: 1.0
});
const blueBulletMat = new THREE.MeshStandardMaterial({
color: 0x0088ff, emissive: 0x004488, emissiveIntensity: 1.0, metalness: 0.5, roughness: 0.1
});
const yellowBulletMat = new THREE.MeshStandardMaterial({
color: 0xffaa00, emissive: 0xff8800, emissiveIntensity: 0.8, metalness: 0.5, roughness: 0.1
});
const raycaster = new THREE.Raycaster();
const debrisRaycaster = new THREE.Raycaster();
const checkRaycaster = new THREE.Raycaster();
const centerPoint = new THREE.Vector2(0, 0);
let isDigging = false;
let isFilling = false;
let isFiring = false; // 是否正在发射
const keys = { w: false, s: false, a: false, d: false, q: false, e: false, space: false, shift: false };
let yaw = 0, pitch = 0;
// --- 2. 界面与样式 ---
const applyLevelData = (data) => {
// Clear existing turrets
[...turrets, ...innerTurrets].forEach(t => {
scene.remove(t.mesh);
if (t.laser) scene.remove(t.laser);
if (t.element) t.element.remove();
if (t.shield) scene.remove(t.shield);
});
turrets = [];
innerTurrets = [];
// Restore voxels
if (data.voxels && data.voxels.length === effects.length) {
data.voxels.forEach((vData, i) => {
effects[i].field.set(vData);
effects[i].update();
if (effects[i].geometry) {
effects[i].geometry.computeBoundingSphere();
effects[i].geometry.computeBoundingBox();
}
});
}
// Restore turrets
const restoreTurret = (tData) => {
const pos = new THREE.Vector3().fromArray(tData.pos);
const norm = new THREE.Vector3().fromArray(tData.norm);
placeTurret(pos, norm, tData.type);
};
if (data.turrets) data.turrets.forEach(restoreTurret);
if (data.innerTurrets) data.innerTurrets.forEach(restoreTurret);
};
const saveLevel = () => {
if (isTestMode) {
alert("请先退出测试模式 (按H键) 再保存关卡");
return;
}
const data = {
voxels: effects.map(e => Array.from(e.field)),
turrets: turrets.map(t => ({
pos: t.mesh.position.toArray(),
norm: t.mesh.userData.normal.toArray(),
type: t.type
})),
innerTurrets: innerTurrets.map(t => ({
pos: t.mesh.position.toArray(),
norm: t.mesh.userData.normal.toArray(),
type: t.type
}))
};
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'planet_level.json';
a.click();
URL.revokeObjectURL(url);
};
const loadLevel = (event) => {
const file = event.target.files[0];
if (!file) return;
if (isTestMode) {
alert("请先退出测试模式 (按H键) 再加载关卡");
event.target.value = '';
return;
}
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = JSON.parse(e.target.result);
applyLevelData(data);
// Reset file input
event.target.value = '';
console.log("Level loaded successfully!");
} catch (err) {
console.error("Failed to load level:", err);
alert("加载存档失败,文件可能损坏");
}
};
reader.readAsText(file);
};
const setupUI = () => {
const style = document.createElement('style');
style.innerHTML = `
body { margin: 0; overflow: hidden; background: #000; font-family: sans-serif; }
#crosshair {
position: absolute; top: 50%; left: 50%;
width: 20px; height: 20px;
transform: translate(-50%, -50%); pointer-events: none; z-index: 100;
}
#crosshair::before, #crosshair::after {
content: '';
position: absolute;
background: rgba(0, 255, 0, 0.8);
}
#crosshair::before {
width: 2px; height: 100%;
left: 50%; top: 0;
transform: translateX(-50%);
}
#crosshair::after {
width: 100%; height: 2px;
left: 0; top: 50%;
transform: translateY(-50%);
}
#blocker {
position: absolute; width: 100%; height: 100%;
background: rgba(0,0,0,0.5); display: flex; flex-direction: column;
justify-content: center; align-items: center;
color: white; cursor: pointer; z-index: 200;
}
#gui-panel {
position: absolute; top: 20px; right: 20px;
width: 220px; background: rgba(0, 20, 0, 0.85);
color: #0f0; padding: 15px; border-radius: 8px;
border: 1px solid #0f0; z-index: 210;
}
.gui-row { margin-bottom: 12px; }
.gui-row label { display: block; font-size: 12px; margin-bottom: 5px; }
.gui-row input { width: 100%; accent-color: #0f0; cursor: pointer; }
.val-display { float: right; color: white; font-weight: bold; }
#status-container {
position: absolute; bottom: 30px; left: 50%; transform: translateX(-50%);
width: 300px; display: none; flex-direction: column; gap: 5px;
pointer-events: none;
}
.bar-bg { width: 100%; height: 8px; background: rgba(0,0,0,0.6); border: 1px solid #555; border-radius: 4px; overflow: hidden; }
#energy-bar { width: 50%; height: 100%; background: #ff9900; transition: width 0.1s; }
#health-bar { width: 100%; height: 100%; background: #0f0; transition: width 0.2s; }
#heat-bar { width: 0%; height: 100%; background: #ff0000; transition: width 0.05s; }
#boss-hp-container {
position: absolute; top: 30px; left: 50%; transform: translateX(-50%);
width: 600px; height: 20px; display: none;
background: rgba(0,0,0,0.5); border: 2px solid #ff00ff; border-radius: 10px; overflow: hidden;
z-index: 150;
}
#boss-hp-bar { width: 100%; height: 100%; background: #ff00ff; transition: width 0.1s; }
#victory-screen {
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0, 0, 0, 0.7); display: none; flex-direction: column;
justify-content: center; align-items: center; z-index: 300;
color: gold;
}
#victory-text { font-size: 80px; font-weight: bold; text-shadow: 0 0 20px #fff; margin-bottom: 30px; }
#defeat-screen {
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0, 0, 0, 0.7); display: none; flex-direction: column;
justify-content: center; align-items: center; z-index: 300;
color: #ff3333;
}
#defeat-text { font-size: 80px; font-weight: bold; text-shadow: 0 0 20px #f00; margin-bottom: 30px; }
#close-btn, #restart-btn {
padding: 10px 30px; background: #fff; color: #000; border: none;
font-size: 20px; cursor: pointer; border-radius: 5px; font-weight: bold;
pointer-events: auto;
}
#close-btn:hover, #restart-btn:hover { background: #ccc; }
.turret-hp {
position: absolute; width: 40px; height: 4px; background: red;
display: none; pointer-events: none; z-index: 50; transform: translate(-50%, -50%);
}
.turret-hp-inner { width: 100%; height: 100%; background: #0f0; }
`;
document.head.appendChild(style);
const gameTitle = document.createElement('div');
gameTitle.innerText = "Interstellar Demolition Office";
gameTitle.style.position = 'absolute';
gameTitle.style.top = '15px';
gameTitle.style.left = '15px';
gameTitle.style.color = '#0f0';
gameTitle.style.fontSize = '20px';
gameTitle.style.fontWeight = 'bold';
gameTitle.style.fontFamily = 'monospace';
gameTitle.style.zIndex = '100';
gameTitle.style.pointerEvents = 'none';
gameTitle.style.textShadow = '1px 1px 2px black';
document.body.appendChild(gameTitle);
const blocker = document.createElement('div');
blocker.id = 'blocker';
blocker.innerHTML = `
<div style="max-width: 600px; text-align: left; background: rgba(0,0,0,0.8); padding: 20px; border: 1px solid #fff; border-radius: 10px;">
<h2 style="text-align: center; color: #0f0; margin-top: 0;">[Interstellar Demolition Office]</h2>
<p style="font-size: 14px; line-height: 1.5;">Destructible Terrain Space Bullet Hell Shooter Demo, built with the Three.js game engine as a cross-platform browser-based proof of concept.</p>
<br>
<p style="font-size: 14px; line-height: 1.5;">Players pilot a spacecraft and fire two types of ammunition to destroy mineral voxels on the planet's surface.<br>
Once destroyed, mineral voxels shatter into debris, exposing buried enemy facilities.</p>
<br>
<p style="font-size: 14px; line-height: 1.5;">Players must collect special reward minerals from the debris to replenish their health and energy bars.<br>
<span style="color: #ffaa00">Gold shards</span> restore Energy (required for <span style="color: #ff0000">Heavy Shots</span>).<br>
<span style="color: #00aaaa">Crystal shards</span> restore Health.<br>
After destroying all enemy units, the core is unlocked.<br>
The core contains dense enemy installations; defeating all of them completes the level.</p>
<p>This game is made by sdsds222</p>
<hr style="border: 0; border-top: 1px solid #555; margin: 15px 0;">
<h3 style="color: #0f0; font-size: 16px; margin-bottom: 10px; text-align: center;">CONTROLS</h3>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px 20px; font-size: 13px; color: #ccc; margin-bottom: 20px;">
<div style="text-align: right; color: #fff;">W / A / S / D</div><div>Rotate Orbit</div>
<div style="text-align: right; color: #fff;">Q / E</div><div>Zoom In / Out</div>
<div style="text-align: right; color: #fff;">SHIFT</div><div>Precision Mode</div>
<div style="text-align: right; color: #fff;">MOUSE</div><div>Aim / Look</div>
<div style="text-align: right; color: #fff;">L. CLICK</div><div>Fire Weapon</div>
<div style="text-align: right; color: #fff;">SCROLL</div><div>Switch Weapon</div>
<div style="text-align: right; color: #fff;">L</div><div>Toggle Edit Mode</div>
</div>
<div style="text-align: center; margin-top: 20px;">
<button id="continue-btn" style="padding: 10px 30px; font-size: 18px; cursor: pointer; background: #0f0; color: #000; border: none; font-weight: bold; border-radius: 5px;">CONTINUE</button>
</div>
</div>
`;
document.body.appendChild(blocker);
const gui = document.createElement('div');
gui.id = 'gui-panel';
gui.style.display = 'none'; // 隐藏右上角UI
gui.innerHTML = `
<div class="gui-row"><label>工具: <span id="current-name" class="val-display">石材</span></label></div>
<div class="gui-row">
<label>笔刷大小: <span id="radius-val" class="val-display">2.0</span></label>
<input type="range" id="radius-slider" min="0.5" max="12" step="0.1" value="2.0">
</div>
<div class="gui-row">
<label>速度: <span id="strength-val" class="val-display">5.0</span></label>
<input type="range" id="strength-slider" min="0.5" max="20" step="0.1" value="5.0">
</div>
<div class="gui-row" style="margin-top: 15px; padding-top: 10px; border-top: 1px solid #0f0;">
<button id="save-btn" style="width: 48%; background: #003300; color: #0f0; border: 1px solid #0f0; cursor: pointer;">保存</button>
<button id="load-btn" style="width: 48%; background: #003300; color: #0f0; border: 1px solid #0f0; cursor: pointer;">加载</button>
<input type="file" id="level-input" style="display:none" accept=".json">
</div>
`;
document.body.appendChild(gui);
const statusContainer = document.createElement('div');
statusContainer.id = 'status-container';
statusContainer.innerHTML = `
<div id="weapon-display" style="text-align:center; color:#fff; font-weight:bold; text-shadow:1px 1px 2px black; margin-bottom:5px;"></div>
<div class="bar-bg"><div id="energy-bar"></div></div>
<div class="bar-bg" style="border-color:#0f0;"><div id="health-bar"></div></div>
<div class="bar-bg" style="border-color:#ff0000;"><div id="heat-bar"></div></div>
`;
document.body.appendChild(statusContainer);
const bossHpContainer = document.createElement('div');
bossHpContainer.id = 'boss-hp-container';
bossHpContainer.innerHTML = `<div id="boss-hp-bar"></div>`;
document.body.appendChild(bossHpContainer);
const vic = document.createElement('div');
vic.id = 'victory-screen';
vic.innerHTML = `<div id="victory-text">MISSION COMPLETE</div><button id="close-btn">Close</button>`;
document.body.appendChild(vic);
const defeat = document.createElement('div');
defeat.id = 'defeat-screen';
defeat.innerHTML = `<div id="defeat-text">MISSION FAILED</div><button id="restart-btn">Restart</button>`;
document.body.appendChild(defeat);
document.getElementById('close-btn').addEventListener('click', () => {
resetScene(); // 重置场景
vic.style.display = 'none';
document.getElementById('blocker').style.display = 'flex';
});
document.getElementById('restart-btn').addEventListener('click', () => {
resetScene(); // 重置场景
defeat.style.display = 'none';
renderer.domElement.requestPointerLock();
});
document.getElementById('continue-btn').addEventListener('click', () => renderer.domElement.requestPointerLock());
document.addEventListener('pointerlockchange', () => {
if (document.pointerLockElement === renderer.domElement) {
blocker.style.display = 'none';
} else {
if (!isVictory && !isDead) {
blocker.style.display = 'flex';
} else {
blocker.style.display = 'none';
}
}
});
const ch = document.createElement('div');
ch.id = 'crosshair';
document.body.appendChild(ch);
document.getElementById('radius-slider').addEventListener('input', (e) => { BRUSH_RADIUS = parseFloat(e.target.value); updateUIFeedback(); });
document.getElementById('strength-slider').addEventListener('input', (e) => { EDIT_STRENGTH = parseFloat(e.target.value); updateUIFeedback(); });
document.getElementById('save-btn').addEventListener('click', saveLevel);
document.getElementById('load-btn').addEventListener('click', () => document.getElementById('level-input').click());
document.getElementById('level-input').addEventListener('change', loadLevel);
};
const updateUIFeedback = () => {
const modeObj = allModes[currentModeIndex];
const name = typeof modeObj === 'string' ? modeObj : modeObj.name;
const isWep = modeObj.isWeapon;
const nameEl = document.getElementById('current-name');
const radSlider = document.getElementById('radius-slider');
const radVal = document.getElementById('radius-val');
const strSlider = document.getElementById('strength-slider');
const strVal = document.getElementById('strength-val');
const statusCont = document.getElementById('status-container');
const hBar = document.getElementById('health-bar');
const eBar = document.getElementById('energy-bar');
const heatBar = document.getElementById('heat-bar');
const bossCont = document.getElementById('boss-hp-container');
const bossBar = document.getElementById('boss-hp-bar');
const weaponDisplay = document.getElementById('weapon-display');
if (nameEl) {
let displayName = name;
nameEl.innerText = displayName;
if (isWep) {
nameEl.style.color = "#ff0000";
} else if (modeObj.isTurret) {
if (modeObj.type === 'tracking') nameEl.style.color = "#0088ff";
else if (modeObj.type === 'basic') nameEl.style.color = "#ffaa00";
else nameEl.style.color = "#ffff00";
} else {
nameEl.style.color = "#ffffff";
}
if (weaponDisplay) {
weaponDisplay.innerText = displayName;
weaponDisplay.style.color = nameEl.style.color;
}
}
if (radSlider) radSlider.value = BRUSH_RADIUS;
if (radVal) radVal.innerText = BRUSH_RADIUS.toFixed(1);
if (strSlider) strSlider.value = EDIT_STRENGTH;
if (strVal) strVal.innerText = EDIT_STRENGTH.toFixed(1);
if (statusCont) statusCont.style.display = isTestMode ? 'flex' : 'none';
if (hBar) {
hBar.style.width = playerHealth + '%';
hBar.style.backgroundColor = playerHealth > 50 ? '#0f0' : '#f00';
}
if (eBar) {
eBar.style.width = shipEnergy + '%';
}
if (heatBar) {
heatBar.style.width = weaponHeat + '%';
heatBar.style.backgroundColor = isOverheated ? '#ff0000' : '#ffaa00';
}
if (bossCont) {
if (isTestMode && isPhaseTwo && !isVictory && innerTurrets.length > 0) {
bossCont.style.display = 'block';
let totalHp = 0;
innerTurrets.forEach(t => totalHp += t.health);
const maxTotal = innerTurrets.length * 300;
if (maxTotal > 0) bossBar.style.width = (totalHp / maxTotal * 100) + '%';
} else {
bossCont.style.display = 'none';
}
}
};
const createExplosion = (pos, color, count) => {
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(count * 3);
const velocities = [];
for (let i = 0; i < count; i++) {
positions[i * 3] = pos.x; positions[i * 3 + 1] = pos.y; positions[i * 3 + 2] = pos.z;
velocities.push(new THREE.Vector3((Math.random() - 0.5) * 0.6, (Math.random() - 0.5) * 0.6, (Math.random() - 0.5) * 0.6));
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const points = new THREE.Points(geometry, new THREE.PointsMaterial({ color: color, size: 0.15, transparent: true, opacity: 1 }));
scene.add(points);
particleGroups.push({ mesh: points, velocities: velocities, life: 1.0 });
};
const createRockDebris = (pos, bulletDir, destroyedMatIdx, destroyedAmount, hitObject, minS, maxS) => {
if (hitObject === planetCore) return;
const baseDir = bulletDir.clone().multiplyScalar(-1);
// 计算碎片数量:与破坏量成正比
let normalDebrisCount = Math.floor(destroyedAmount * 50);
// 黄金和水晶产生更少的碎片(减半)
if (destroyedMatIdx === 1 || destroyedMatIdx === 2) {
normalDebrisCount = Math.floor(normalDebrisCount * 0.5);
}
normalDebrisCount = Math.max(0, Math.min(normalDebrisCount, 100)); // 限制最大碎片数量
// 炮台爆炸产生奖励碎片(黄金、水晶、绿色)- 100%掉落
let goldRewardCount = 0, crystalRewardCount = 0, speedRewardCount = 0;
if (hitObject.userData && hitObject.userData.isTurret) {
// 炮台爆炸时100%掉落黄金、水晶、绿色碎片各1个
goldRewardCount = 1;
crystalRewardCount = 1;
//speedRewardCount = 1;
normalDebrisCount = Math.max(2, normalDebrisCount); // 炮台至少5个碎片
}
// 如果破坏的是黄金或水晶,使用累积机制产生奖励碎片
if (destroyedMatIdx === 1) { // 黄金
goldAccumulator += destroyedAmount;
while (goldAccumulator >= GOLD_THRESHOLD) {
goldRewardCount++;
goldAccumulator -= GOLD_THRESHOLD;
}
} else if (destroyedMatIdx === 2) { // 水晶
crystalAccumulator += destroyedAmount;
while (crystalAccumulator >= CRYSTAL_THRESHOLD) {
crystalRewardCount++;
crystalAccumulator -= CRYSTAL_THRESHOLD;
}
}
// 生成普通碎片(使用被破坏材质的外观)
for (let i = 0; i < normalDebrisCount; i++) {
let selectedMat;
let massSpeedMulti = 1.0;
let damageMultiplier = 1.0;
// 根据被破坏的材质选择碎片材质
if (destroyedMatIdx !== null && destroyedMatIdx >= 0 && destroyedMatIdx < effects.length) {
selectedMat = effects[destroyedMatIdx].material;
// 根据材质设置物理属性
if (destroyedMatIdx === 3) { // 铁矿
massSpeedMulti = 0.3; // 更重
damageMultiplier = 3.0; // 伤害更大
} else if (destroyedMatIdx === 1) { // 黄金
massSpeedMulti = 0.8;
damageMultiplier = 0.5;
} else if (destroyedMatIdx === 2) { // 水晶
massSpeedMulti = 1.0;
damageMultiplier = 0.5;
} else { // 石材
massSpeedMulti = 1.0;
damageMultiplier = 1.0;
}
} else {
selectedMat = hitObject.material || effects[0].material;
massSpeedMulti = 1.0;
}
const debrisMaterial = selectedMat.clone();
debrisMaterial.flatShading = false;
debrisMaterial.side = THREE.FrontSide;
debrisMaterial.envMap = globalSkybox;
// 水晶碎片不透明,其他材质保持透明
debrisMaterial.transparent = (destroyedMatIdx !== 2);
if (destroyedMatIdx === 2) {
debrisMaterial.opacity = 1.0; // 水晶碎片完全不透明
}
const velocity = baseDir.clone().add(new THREE.Vector3((Math.random() - 0.5) * 0.15, (Math.random() - 0.5) * 0.15, (Math.random() - 0.5) * 0.15)).normalize().multiplyScalar((0.04 + Math.random() * 0.08) * massSpeedMulti);
const baseSize = (minS + Math.random() * (maxS - minS));
const geometry = new THREE.IcosahedronGeometry(baseSize, 1);
const positions = geometry.attributes.position;
const vertexMap = new Map();
for (let j = 0; j < positions.count; j++) {
const v = new THREE.Vector3().fromBufferAttribute(positions, j);
const key = `${v.x.toFixed(4)}_${v.y.toFixed(4)}_${v.z.toFixed(4)}`;
if (!vertexMap.has(key)) vertexMap.set(key, 0.8 + Math.random() * 0.4);
v.normalize().multiplyScalar(baseSize * vertexMap.get(key));
positions.setXYZ(j, v.x, v.y, v.z);
}
positions.needsUpdate = true;
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(geometry, debrisMaterial);
mesh.position.copy(pos);
mesh.scale.set(0.5 + Math.random() * 1.5, 0.5 + Math.random() * 1.5, 0.5 + Math.random() * 1.5);
mesh.rotation.set(Math.random() * 6, Math.random() * 6, Math.random() * 6);
mesh.layers.enable(0);
mesh.layers.enable(1);
const rotVel = { x: (Math.random() - 0.5) * 0.04, y: (Math.random() - 0.5) * 0.04, z: (Math.random() - 0.5) * 0.04 };
rockDebris.push({
mesh: mesh, velocity: velocity, rotVel: rotVel, life: 3.0, age: 0, bSize: baseSize, canFade: false,
isHeal: false,
isAmmo: false,
damageMultiplier: damageMultiplier
});
scene.add(mesh);
}
// 单独生成黄金奖励碎片(能量)- 使用黄金材质,适中尺寸
for (let i = 0; i < goldRewardCount; i++) {
const baseSize = (minS + Math.random() * (maxS - minS)) * 2.0; // 2倍大小
const geometry = new THREE.IcosahedronGeometry(baseSize, 1);
const positions = geometry.attributes.position;
const vertexMap = new Map();
for (let j = 0; j < positions.count; j++) {
const v = new THREE.Vector3().fromBufferAttribute(positions, j);
const key = `${v.x.toFixed(4)}_${v.y.toFixed(4)}_${v.z.toFixed(4)}`;
if (!vertexMap.has(key)) vertexMap.set(key, 0.8 + Math.random() * 0.4);
v.normalize().multiplyScalar(baseSize * vertexMap.get(key)); positions.setXYZ(j, v.x, v.y, v.z);
}
positions.needsUpdate = true; geometry.computeVertexNormals();
// 使用黄金材质(带环境映射和金属感)
const goldMat = new THREE.MeshStandardMaterial({
color: 0xffaa00,
metalness: 0.6,
roughness: 0.2,
envMap: globalSkybox,
emissive: 0xaa7700,
emissiveIntensity: 0.3
});
const mesh = new THREE.Mesh(geometry, goldMat);
mesh.position.copy(pos);
mesh.scale.set(0.5 + Math.random() * 1.5, 0.5 + Math.random() * 1.5, 0.5 + Math.random() * 1.5);
mesh.rotation.set(Math.random() * 6, Math.random() * 6, Math.random() * 6);
const outlineMesh = new THREE.Mesh(geometry, rewardOutlineMat);
outlineMesh.scale.setScalar(1.2);
mesh.add(outlineMesh);
mesh.layers.enable(0);
mesh.layers.enable(1);
// 速度与普通碎片一致
const velocity = baseDir.clone().add(new THREE.Vector3((Math.random() - 0.5) * 0.15, (Math.random() - 0.5) * 0.15, (Math.random() - 0.5) * 0.15)).normalize().multiplyScalar(0.04 + Math.random() * 0.08);
const rotVel = { x: (Math.random() - 0.5) * 0.04, y: (Math.random() - 0.5) * 0.04, z: (Math.random() - 0.5) * 0.04 };
rockDebris.push({
mesh: mesh, velocity: velocity, rotVel: rotVel, life: 3.0, age: 0, bSize: baseSize, canFade: false,
isHeal: false,
isAmmo: true,
damageMultiplier: 1.0
});
scene.add(mesh);
}
// 单独生成水晶奖励碎片(治疗)- 使用水晶材质,适中尺寸
for (let i = 0; i < crystalRewardCount; i++) {
const baseSize = (minS + Math.random() * (maxS - minS)) * 2.0; // 2倍大小
const geometry = new THREE.IcosahedronGeometry(baseSize, 1);
const positions = geometry.attributes.position;
const vertexMap = new Map();
for (let j = 0; j < positions.count; j++) {
const v = new THREE.Vector3().fromBufferAttribute(positions, j);
const key = `${v.x.toFixed(4)}_${v.y.toFixed(4)}_${v.z.toFixed(4)}`;
if (!vertexMap.has(key)) vertexMap.set(key, 0.8 + Math.random() * 0.4);
v.normalize().multiplyScalar(baseSize * vertexMap.get(key)); positions.setXYZ(j, v.x, v.y, v.z);
}
positions.needsUpdate = true; geometry.computeVertexNormals();
// 使用水晶材质(降低透明度,更暗,更粗糙)
const crystalMat = new THREE.MeshStandardMaterial({
color: 0x00aaaa,
transparent: true,
opacity: 0.4,
roughness: 0.4,
metalness: 0.2,
emissive: 0x005555,
emissiveIntensity: 0.2
});
const mesh = new THREE.Mesh(geometry, crystalMat);
mesh.position.copy(pos);
mesh.scale.set(0.5 + Math.random() * 1.5, 0.5 + Math.random() * 1.5, 0.5 + Math.random() * 1.5);
mesh.rotation.set(Math.random() * 6, Math.random() * 6, Math.random() * 6);
const outlineMesh = new THREE.Mesh(geometry, rewardOutlineMat);
outlineMesh.scale.setScalar(1.2);
mesh.add(outlineMesh);
mesh.layers.enable(0);
mesh.layers.enable(1);
// 速度与普通碎片一致
const velocity = baseDir.clone().add(new THREE.Vector3((Math.random() - 0.5) * 0.15, (Math.random() - 0.5) * 0.15, (Math.random() - 0.5) * 0.15)).normalize().multiplyScalar(0.04 + Math.random() * 0.08);
const rotVel = { x: (Math.random() - 0.5) * 0.04, y: (Math.random() - 0.5) * 0.04, z: (Math.random() - 0.5) * 0.04 };
rockDebris.push({
mesh: mesh, velocity: velocity, rotVel: rotVel, life: 3.0, age: 0, bSize: baseSize, canFade: false,
isHeal: true,
isAmmo: false,
isSpeed: false,
damageMultiplier: 1.0
});
scene.add(mesh);
}
// 单独生成绿色碎片(移速提升)- 使用绿色材质,适中尺寸
for (let i = 0; i < speedRewardCount; i++) {
const baseSize = (minS + Math.random() * (maxS - minS)) * 2.0; // 2倍大小
const geometry = new THREE.IcosahedronGeometry(baseSize, 1);
const positions = geometry.attributes.position;
const vertexMap = new Map();
for (let j = 0; j < positions.count; j++) {
const v = new THREE.Vector3().fromBufferAttribute(positions, j);
const key = `${v.x.toFixed(4)}_${v.y.toFixed(4)}_${v.z.toFixed(4)}`;
if (!vertexMap.has(key)) vertexMap.set(key, 0.8 + Math.random() * 0.4);
v.normalize().multiplyScalar(baseSize * vertexMap.get(key)); positions.setXYZ(j, v.x, v.y, v.z);
}
positions.needsUpdate = true; geometry.computeVertexNormals();
// 使用绿色材质
const speedMat = new THREE.MeshStandardMaterial({
color: 0x00ff00,
metalness: 0.5,
roughness: 0.3,
emissive: 0x00aa00,
emissiveIntensity: 0.4
});
const mesh = new THREE.Mesh(geometry, speedMat);
mesh.position.copy(pos);
mesh.scale.set(0.5 + Math.random() * 1.5, 0.5 + Math.random() * 1.5, 0.5 + Math.random() * 1.5);
mesh.rotation.set(Math.random() * 6, Math.random() * 6, Math.random() * 6);
const outlineMesh = new THREE.Mesh(geometry, rewardOutlineMat);
outlineMesh.scale.setScalar(1.2);
mesh.add(outlineMesh);
mesh.layers.enable(0);
mesh.layers.enable(1);
// 速度与普通碎片一致
const velocity = baseDir.clone().add(new THREE.Vector3((Math.random() - 0.5) * 0.15, (Math.random() - 0.5) * 0.15, (Math.random() - 0.5) * 0.15)).normalize().multiplyScalar(0.04 + Math.random() * 0.08);
const rotVel = { x: (Math.random() - 0.5) * 0.04, y: (Math.random() - 0.5) * 0.04, z: (Math.random() - 0.5) * 0.04 };
rockDebris.push({
mesh: mesh, velocity: velocity, rotVel: rotVel, life: 3.0, age: 0, bSize: baseSize, canFade: false,
isHeal: false,
isAmmo: false,
isSpeed: true,
damageMultiplier: 1.0
});
scene.add(mesh);
}
};
const fireBullet = () => {
const modeObj = allModes[currentModeIndex];
if (!modeObj || !modeObj.isWeapon) return;
// 常规弹检查过热
if (!modeObj.isHeavy && isOverheated) {
return;
}
// 常规弹检查射速限制
if (!modeObj.isHeavy) {
const now = Date.now();
if (now - lastFireTime < FIRE_COOLDOWN) {
return;
}
lastFireTime = now;
}
if (isTestMode && modeObj.isHeavy) {
if (shipEnergy < ENERGY_COST) {
console.log("能量不足!请采集橙色碎片");
return;
}
shipEnergy -= ENERGY_COST;
}
// 常规弹增加热量
if (!modeObj.isHeavy) {
weaponHeat = Math.min(MAX_HEAT, weaponHeat + HEAT_PER_SHOT);
if (weaponHeat >= OVERHEAT_THRESHOLD) {
isOverheated = true;
}
}
updateUIFeedback();
const bullet = new THREE.Mesh(new THREE.SphereGeometry(modeObj.size, 8, 8), new THREE.MeshBasicMaterial({ color: modeObj.color }));
let spawnPos;
if (isTestMode && playerShip) {
spawnPos = playerShip.position.clone().add(
new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion)
);
} else {
spawnPos = camera.position.clone();
}
bullet.position.copy(spawnPos);
raycaster.setFromCamera(centerPoint, camera);
const intersects = raycaster.intersectObjects([...effects, planetCore]);
let targetPoint;
if (intersects.length > 0) {
targetPoint = intersects[0].point;
} else {
targetPoint = raycaster.ray.origin.clone().add(raycaster.ray.direction.clone().multiplyScalar(1000));
}
const dir = targetPoint.clone().sub(spawnPos).normalize();
const speed = modeObj.isHeavy ? 1.2 : 1.8;
bullets.push({ mesh: bullet, direction: dir, speed: speed, life: 100, config: modeObj });
scene.add(bullet);
};
const createCoreLaser = (startPos) => {
const geometry = new THREE.BufferGeometry().setFromPoints([startPos, new THREE.Vector3(0, 0, 0)]);
const line = new THREE.Line(geometry, laserMat);
scene.add(line);
return line;
};
const placeTurret = (pos, normal, modeType) => {
const distToCenter = pos.length();
const isInner = (distToCenter < 1.5);
const size = isInner ? 0.25 : 0.5;
const geometry = new THREE.BoxGeometry(size, size, size);
const isTracking = (modeType === 'tracking');
const isBasic = (modeType === 'basic');
let mat;
if (isTracking) mat = turretMatBlue;
else if (isBasic) mat = turretMatYellow;
else mat = turretMatRed;
const mesh = new THREE.Mesh(geometry, mat);
mesh.material.envMap = globalSkybox;
mesh.position.copy(pos).add(normal.multiplyScalar(size * 0.5));
mesh.userData.isTurret = true;
mesh.userData.normal = normal.clone().normalize();
mesh.userData.firePoint = mesh.position.clone().add(normal.multiplyScalar(0.4));
mesh.lookAt(pos.clone().add(normal));
mesh.layers.enable(0);
mesh.layers.enable(1);
// 添加红色边框(炮台专用)
const turretOutlineMat = new THREE.MeshBasicMaterial({ color: 0xff0000, side: THREE.BackSide }); // 红色
const outlineGeo = new THREE.BoxGeometry(size * 1.15, size * 1.15, size * 1.15);
const outlineMesh = new THREE.Mesh(outlineGeo, turretOutlineMat);
mesh.add(outlineMesh);
let shield;
// 只有标准炮台(红色)有护盾,基础炮台(黄色)和追踪炮台(蓝色)无护盾
if (!isTracking && !isBasic) {
const shieldGeo = new THREE.SphereGeometry(size * 1.2, 16, 16);
shield = new THREE.Mesh(shieldGeo, shieldMat);
shield.visible = false;
mesh.add(shield);
}
scene.add(mesh);
let laser;
if (!isInner) {
laser = createCoreLaser(mesh.position);
}
const hpDiv = document.createElement('div');
hpDiv.className = 'turret-hp';
hpDiv.innerHTML = '<div class="turret-hp-inner"></div>';
document.body.appendChild(hpDiv);
const turretObj = {
mesh: mesh,
shield: shield,
laser: laser,
health: isInner ? 300 : 100,
active: false,
cooldown: 0,
element: hpDiv,
hpInner: hpDiv.children[0],
type: modeType
};
if (isInner) {
mesh.userData.isInnerTurret = true;
innerTurrets.push(turretObj);
} else {
turrets.push(turretObj);
}
};
const spawnEnemyBullet = (startPos, velocity, type = 'red', isFromInner = false) => {
let mat;
if (type === 'blue') mat = blueBulletMat.clone();
else if (type === 'yellow') mat = yellowBulletMat.clone();
else mat = enemyBulletMat.clone();
const size = (type === 'core') ? 0.15 : 0.08;
const bullet = new THREE.Mesh(new THREE.SphereGeometry(size, 8, 8), mat);
bullet.position.copy(startPos);
bullet.layers.enable(0);
bullet.layers.enable(1);
enemyBullets.push({
mesh: bullet,
velocity: velocity,
canFade: false,
fadeLife: 1.0,
type: type, // 'red', 'blue', 'yellow', 'core'
speed: velocity.length(),
isCore: (type === 'core'),
isFromInner: isFromInner // 标记是否来自内部炮台
});
scene.add(bullet);
}
const fireTurretBullet = (t) => {
let baseDir = playerShip.position.clone().sub(t.mesh.userData.firePoint).normalize();
const isInner = t.mesh.userData.isInnerTurret || false;
if (t.type === 'tracking') {
// 蓝色追踪炮台
let spread = new THREE.Vector3((Math.random() - 0.5) * 0.3, (Math.random() - 0.5) * 0.3, (Math.random() - 0.5) * 0.3);
let finalDir = baseDir.add(spread).normalize();
spawnEnemyBullet(t.mesh.userData.firePoint, finalDir.multiplyScalar(0.04), 'blue', isInner);
t.cooldown = 30 + Math.random() * 120;
} else if (t.type === 'basic') {
// 黄色基础炮台 - 更快更准
let spread = new THREE.Vector3((Math.random() - 0.5) * 0.1, (Math.random() - 0.5) * 0.1, (Math.random() - 0.5) * 0.1); // 从0.2改为0.1,更准