-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathEnemySpawnManager.cs
More file actions
1113 lines (938 loc) · 40.4 KB
/
EnemySpawnManager.cs
File metadata and controls
1113 lines (938 loc) · 40.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
using System;
using System.Collections.Generic;
using Godot;
using Godot.Collections;
using Kuros.Core;
namespace Kuros.Controllers
{
/// <summary>
/// 进入触发范围后批量生成敌人的管理器。
/// 支持选择敌人场景、生成数量、触发范围,以及前后景出场动画。
/// </summary>
[Tool]
[GlobalClass]
public partial class EnemySpawnManager : Node2D
{
public enum BackEffectSpawnGateMode
{
Delay,
BackEffectFrame,
BackEffectFinished
}
public enum EnemySelectionMode
{
Sequential,
Random
}
[Signal] public delegate void SpawnStartedEventHandler();
[Signal] public delegate void EnemySpawnedEventHandler(Node enemy, int index);
[Signal] public delegate void SpawnCompletedEventHandler();
[ExportCategory("Enemy")]
[Export] public PackedScene EnemyScene { get; set; } = null!;
[Export] public Array<PackedScene> EnemyScenes { get; set; } = new();
[Export] public EnemySelectionMode MultiEnemySelectionMode { get; set; } = EnemySelectionMode.Sequential;
[Export] public bool SpawnCountPerEnemyType { get; set; } = false;
[Export(PropertyHint.Range, "1,100,1")] public int SpawnCount { get; set; } = 1;
[Export(PropertyHint.Range, "0,10,0.05")] public float SpawnInterval { get; set; } = 0.15f;
[Export] public NodePath SpawnParentPath { get; set; } = new NodePath();
[Export] public bool SpawnOnReady { get; set; } = false;
[Export] public bool TriggerOnce { get; set; } = true;
[Export] public bool SimultaneousSpawn { get; set; } = false; // 是否同时生成所有敌人
/// <summary>
/// 是否启用自动触发器(TriggerArea)。
/// 作为 WaveSpawnManager 的子波次时应设为 false,由 WaveSpawnManager 统一驱动。
/// </summary>
[Export] public bool EnableTrigger { get; set; } = true;
[ExportCategory("Trigger")]
[Export] public Area2D? TriggerArea { get; set; }
[Export] public bool AutoConfigureAssignedTriggerArea { get; set; } = false;
[Export] public string TriggerGroupName { get; set; } = "player";
[Export] public Vector2 TriggerOffset { get; set; } = Vector2.Zero;
[Export] public Vector2 TriggerSize { get; set; } = new Vector2(320, 180);
[Export] public uint TriggerCollisionLayer { get; set; } = 0;
[Export] public uint TriggerCollisionMask { get; set; } = uint.MaxValue;
[ExportCategory("Spawn Placement")]
[Export] public bool UseExplicitSpawnOffsets { get; set; } = false;
[Export] public Array<Vector2> SpawnOffsets { get; set; } = new();
[Export] public Vector2 SpawnAreaExtents { get; set; } = new Vector2(96, 48);
[Export] public Vector2 EnemySpawnOffset { get; set; } = Vector2.Zero;
[Export] public bool AlignEnemyFacingToManager { get; set; } = true;
[Export] public bool FaceRightOnSpawn { get; set; } = false;
// 智能落点检测:优先生成在无障碍物的位置(默认检测 Layer 1,即家具/环境静态体)
[Export] public bool EnableSmartSpawnPlacement { get; set; } = true;
[Export(PropertyHint.Layers2DPhysics)] public uint ObstacleCheckMask { get; set; } = 1u; //检测障碍物的层,默认Layer 1
[Export(PropertyHint.Range, "1,30,1")] public int MaxSpawnAttempts { get; set; } = 10;
[Export(PropertyHint.Range, "4,500,2")] public float SpawnCheckRadius { get; set; } = 60f; // 生成点周围这个半径范围内如果有障碍物则视为不合适的落点
private const string DefaultBackEffectPath = "res://scenes/actors/etc/enemy_spaw_back.tscn";
private const string DefaultFrontEffectPath = "res://scenes/actors/etc/enemy_spawn_front.tscn";
// 按需加载的运行时特效场景(在 SpawnSequenceAsync 期间加载,结束后释放)
private PackedScene? _runtimeBackEffectScene;
private PackedScene? _runtimeFrontEffectScene;
[ExportCategory("Spawn FX")]
[Export] public PackedScene? SpawnBackEffectScene { get; set; }
[Export] public PackedScene? SpawnFrontEffectScene { get; set; }
[Export] public Vector2 SpawnBackEffectOffset { get; set; } = Vector2.Zero;
[Export] public Vector2 SpawnFrontEffectOffset { get; set; } = Vector2.Zero;
[Export(PropertyHint.Range, "0,5,0.05")] public float EnemyAppearDelay { get; set; } = 0.2f;
[Export] public BackEffectSpawnGateMode EnemyAppearGateMode { get; set; } = BackEffectSpawnGateMode.Delay;
[Export(PropertyHint.Range, "0,300,1")] public int BackEffectAppearFrame { get; set; } = 8;
[Export(PropertyHint.Range, "0,10,0.05")] public float BackEffectGateTimeout { get; set; } = 3f;
[Export] public bool FallbackToDelayWhenGateUnavailable { get; set; } = true;
[Export] public bool AutoLowerFrontEffectAfterEnemySpawn { get; set; } = false;
[Export(PropertyHint.Range, "0,5,0.05")] public float FrontEffectLowerDelay { get; set; } = 0f;
[Export(PropertyHint.Range, "-1000,1000,1")] public int FrontEffectPostSpawnZOffset { get; set; } = -1;
// [ExportCategory("Y-Sort")]
// [Export] public bool EnableYAxisAutoLayering { get; set; } = false;
// [Export(PropertyHint.Range, "0.1,20,0.1")] public float YAxisZScale { get; set; } = 1f;
// [Export(PropertyHint.Range, "-10000,10000,1")] public int YAxisZBase { get; set; } = 0;
// [Export] public bool ClampYAxisZRange { get; set; } = true;
// [Export(PropertyHint.Range, "-10000,10000,1")] public int YAxisZMin { get; set; } = -200;
// [Export(PropertyHint.Range, "-10000,10000,1")] public int YAxisZMax { get; set; } = 400;
// [Export(PropertyHint.Range, "-1000,1000,1")] public int EnemyZOffset { get; set; } = 0;
[ExportCategory("Debug")]
[Export] public bool ShowDebugOverlay { get; set; } = true;
[Export] public bool ShowDebugOverlayInGame { get; set; } = true;
[Export] public bool LogSpawnEffectPositions { get; set; } = true;
[Export] public Color TriggerDebugColor { get; set; } = new Color(0.2f, 0.8f, 1f, 0.9f);
[Export] public Color SpawnDebugColor { get; set; } = new Color(1f, 0.85f, 0.25f, 0.9f);
[Export] public Color ExplicitPointDebugColor { get; set; } = new Color(1f, 0.45f, 0.2f, 1f);
[Export] public Color BackEffectPointColor { get; set; } = new Color(0.4f, 0.9f, 1f, 1f);
[Export] public Color FrontEffectPointColor { get; set; } = new Color(1f, 0.5f, 0.9f, 1f);
[Export(PropertyHint.Range, "1,8,0.5")] public float DebugLineWidth { get; set; } = 2f;
[Export(PropertyHint.Range, "2,16,0.5")] public float DebugPointRadius { get; set; } = 5f;
private readonly RandomNumberGenerator _rng = new();
private CollisionShape2D? _triggerShape;
private bool _hasTriggered;
private bool _isSpawning;
private bool _triggerAreaAutoCreated;
private CircleShape2D? _spawnCheckShape;
public override void _Ready()
{
_rng.Randomize();
if (EnableTrigger)
{
EnsureTriggerArea();
UpdateTriggerAreaShape();
}
if (Engine.IsEditorHint())
{
return;
}
if (EnableTrigger && TriggerArea != null)
{
TriggerArea.BodyEntered += OnTriggerBodyEntered;
}
if (SpawnOnReady)
{
StartSpawnSequence();
}
}
public override void _ExitTree()
{
if (EnableTrigger && TriggerArea != null)
{
TriggerArea.BodyEntered -= OnTriggerBodyEntered;
}
base._ExitTree();
}
public override void _Process(double delta)
{
if (Engine.IsEditorHint() && EnableTrigger)
{
EnsureTriggerArea();
if (ShouldAutoConfigureTriggerArea())
{
UpdateTriggerAreaShape();
}
}
if (ShouldDrawDebugOverlay())
{
QueueRedraw();
}
}
public override void _Draw()
{
if (!ShouldDrawDebugOverlay())
{
return;
}
DrawTriggerDebugShape();
DrawSpawnDebugShape();
DrawExplicitSpawnPoints();
DrawEffectOffsetDebugPoints();
}
public void StartSpawnSequence()
{
if (_isSpawning)
{
return;
}
if (TriggerOnce && _hasTriggered)
{
return;
}
if (LogSpawnEffectPositions)
{
GD.Print($"[{Name}] StartSpawnSequence path={GetPath()}, count={SpawnCount}, interval={SpawnInterval}, enemyDelay={EnemyAppearDelay}, gateMode={EnemyAppearGateMode}, gateFrame={BackEffectAppearFrame}, gateTimeout={BackEffectGateTimeout}, backOffset={SpawnBackEffectOffset}, frontOffset={SpawnFrontEffectOffset}");
}
_ = SpawnSequenceAsync();
}
public void ResetTrigger()
{
_hasTriggered = false;
}
private async System.Threading.Tasks.Task SpawnSequenceAsync()
{
if (_isSpawning)
{
return;
}
_isSpawning = true;
_hasTriggered = true;
EmitSignal(SignalName.SpawnStarted);
await LoadSpawnEffectScenesAsync();
List<PackedScene> spawnQueue = BuildSpawnQueue();
if (spawnQueue.Count == 0)
{
GD.PushWarning($"{Name}: 未设置可生成的敌人场景,无法开始生成。");
_isSpawning = false;
EmitSignal(SignalName.SpawnCompleted);
return;
}
int spawnTotal = spawnQueue.Count;
if (SimultaneousSpawn)
{
// 同时启动所有敌人的生成流程,互不等待
var tasks = new System.Threading.Tasks.Task[spawnTotal];
for (int i = 0; i < spawnTotal; i++)
{
tasks[i] = SpawnSingleEnemyAsync(spawnQueue[i], i, spawnTotal);
}
await System.Threading.Tasks.Task.WhenAll(tasks);
}
else
{
for (int i = 0; i < spawnTotal; i++)
{
await SpawnSingleEnemyAsync(spawnQueue[i], i, spawnTotal);
if (i < spawnTotal - 1 && SpawnInterval > 0f)
{
var intervalTimer = GetTree().CreateTimer(SpawnInterval);
await ToSignal(intervalTimer, SceneTreeTimer.SignalName.Timeout);
}
}
}
_isSpawning = false;
ReleaseSpawnEffectScenes();
EmitSignal(SignalName.SpawnCompleted);
}
private async System.Threading.Tasks.Task LoadSpawnEffectScenesAsync()
{
bool needBack = SpawnBackEffectScene == null;
bool needFront = SpawnFrontEffectScene == null;
if (!needBack && !needFront)
return;
if (needBack)
ResourceLoader.LoadThreadedRequest(DefaultBackEffectPath);
if (needFront)
ResourceLoader.LoadThreadedRequest(DefaultFrontEffectPath);
if (needBack)
{
while (ResourceLoader.LoadThreadedGetStatus(DefaultBackEffectPath) == ResourceLoader.ThreadLoadStatus.InProgress)
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
_runtimeBackEffectScene = ResourceLoader.LoadThreadedGet(DefaultBackEffectPath) as PackedScene;
}
if (needFront)
{
while (ResourceLoader.LoadThreadedGetStatus(DefaultFrontEffectPath) == ResourceLoader.ThreadLoadStatus.InProgress)
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
_runtimeFrontEffectScene = ResourceLoader.LoadThreadedGet(DefaultFrontEffectPath) as PackedScene;
}
}
private void ReleaseSpawnEffectScenes()
{
_runtimeBackEffectScene = null;
_runtimeFrontEffectScene = null;
}
private async System.Threading.Tasks.Task SpawnSingleEnemyAsync(PackedScene enemyScene, int index, int spawnTotal)
{
Vector2 spawnAnchorPosition = ResolveSpawnPosition(index);
Vector2 enemySpawnPosition = spawnAnchorPosition + EnemySpawnOffset;
SpawnEffectRefs effectRefs = PlaySpawnEffects(spawnAnchorPosition);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
ulong waitStart = Time.GetTicksMsec();
await WaitForEnemyAppearGateAsync(effectRefs.BackEffectInstance);
ulong waitedMs = Time.GetTicksMsec() - waitStart;
if (LogSpawnEffectPositions)
{
GD.Print($"[{Name}] Spawn index={index + 1}/{spawnTotal}, gateMode={EnemyAppearGateMode}, actualWait={waitedMs}ms");
}
var enemy = SpawnEnemy(enemyScene, enemySpawnPosition, index);
if (enemy != null)
{
if (LogSpawnEffectPositions)
{
GD.Print($"[{Name}] Enemy spawned index={index + 1}/{spawnTotal}, anchor={spawnAnchorPosition}, enemyPos={enemySpawnPosition}, enemyOffset={EnemySpawnOffset}, root={DescribeCanvasItem(enemy as CanvasItem)}");
}
if (AutoLowerFrontEffectAfterEnemySpawn)
{
LowerFrontEffectAfterEnemySpawn(effectRefs.FrontEffect, enemy);
}
EmitSignal(SignalName.EnemySpawned, enemy, index);
}
}
public Node? SpawnEnemy(PackedScene enemyScene, Vector2 spawnPosition, int spawnIndex)
{
if (enemyScene == null)
{
GD.PushWarning($"{Name}: EnemyScene 未设置,无法生成敌人。");
return null;
}
var instance = enemyScene.Instantiate();
if (instance == null)
{
GD.PushWarning($"{Name}: 敌人场景实例化失败。scene={enemyScene.ResourcePath}");
return null;
}
var parent = ResolveSpawnParent();
parent.AddChild(instance);
if (instance is Node2D node2D)
{
node2D.GlobalPosition = spawnPosition;
// 保留 enemy 自身场景里的 ZIndex / ZAsRelative / YSort 设置,不在生成器里接管。
// int baseZ = node2D.ZIndex;
// ApplyNodeZIndex(node2D, spawnPosition, baseZ, EnemyZOffset);
node2D.Visible = true;
// Some enemy sub-controllers may toggle visibility/modulate in their own _Ready,
// so we only re-apply visibility here and do not override z ordering.
StabilizeSpawnedEnemyVisualAsync(node2D);
}
EnsureSpawnedEnemyVisible(instance);
if (instance is GameActor actor && AlignEnemyFacingToManager)
{
actor.FlipFacing(FaceRightOnSpawn);
}
if (instance is Node node)
{
node.Name = $"{node.Name}_{spawnIndex + 1}";
}
return instance;
}
private List<PackedScene> BuildSpawnQueue()
{
List<PackedScene> configuredScenes = GetConfiguredEnemyScenes();
List<PackedScene> queue = new();
if (configuredScenes.Count == 0)
{
return queue;
}
int clampedSpawnCount = Mathf.Max(1, SpawnCount);
if (SpawnCountPerEnemyType && configuredScenes.Count > 1)
{
foreach (PackedScene scene in configuredScenes)
{
for (int i = 0; i < clampedSpawnCount; i++)
{
queue.Add(scene);
}
}
if (MultiEnemySelectionMode == EnemySelectionMode.Random)
{
ShuffleSpawnQueue(queue);
}
return queue;
}
for (int i = 0; i < clampedSpawnCount; i++)
{
if (MultiEnemySelectionMode == EnemySelectionMode.Random && configuredScenes.Count > 1)
{
int randomIndex = _rng.RandiRange(0, configuredScenes.Count - 1);
queue.Add(configuredScenes[randomIndex]);
}
else
{
queue.Add(configuredScenes[i % configuredScenes.Count]);
}
}
return queue;
}
public List<PackedScene> GetConfiguredEnemyScenes()
{
List<PackedScene> scenes = new();
foreach (PackedScene scene in EnemyScenes)
{
if (scene != null)
{
scenes.Add(scene);
}
}
if (scenes.Count == 0 && EnemyScene != null)
{
scenes.Add(EnemyScene);
}
return scenes;
}
private void ShuffleSpawnQueue(List<PackedScene> queue)
{
for (int i = queue.Count - 1; i > 0; i--)
{
int swapIndex = _rng.RandiRange(0, i);
(queue[i], queue[swapIndex]) = (queue[swapIndex], queue[i]);
}
}
private async void StabilizeSpawnedEnemyVisualAsync(Node2D enemyNode2D)
{
if (!GodotObject.IsInstanceValid(enemyNode2D))
{
return;
}
for (int i = 0; i < 3; i++)
{
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
if (!GodotObject.IsInstanceValid(enemyNode2D))
{
return;
}
// 保留 enemy 自身场景里的排序设置,不再在这里刷新 ZIndex。
EnsureSpawnedEnemyVisible(enemyNode2D);
}
if (LogSpawnEffectPositions)
{
GD.Print($"[{Name}] Enemy visual stabilization complete: {DescribeCanvasItem(enemyNode2D)}");
}
}
private void EnsureSpawnedEnemyVisible(Node enemyRoot)
{
// Ensure common render nodes are visible and opaque after instantiation.
EnsureCanvasItemVisible(enemyRoot as CanvasItem);
Node? spineNode = enemyRoot.GetNodeOrNull("SpineSprite");
if (spineNode is CanvasItem spineCanvas)
{
EnsureCanvasItemVisible(spineCanvas);
}
Node? spriteNode = enemyRoot.GetNodeOrNull("Sprite2D");
if (spriteNode is CanvasItem spriteCanvas)
{
EnsureCanvasItemVisible(spriteCanvas);
}
if (LogSpawnEffectPositions)
{
string spineInfo = DescribeCanvasItem(spineNode as CanvasItem);
string spriteInfo = DescribeCanvasItem(spriteNode as CanvasItem);
GD.Print($"[{Name}] Enemy visual restore: root={DescribeCanvasItem(enemyRoot as CanvasItem)}, spine={spineInfo}, sprite={spriteInfo}");
}
}
private static void EnsureCanvasItemVisible(CanvasItem? item)
{
if (item == null || !GodotObject.IsInstanceValid(item))
{
return;
}
item.Visible = true;
Color modulate = item.Modulate;
if (modulate.A < 1f)
{
modulate.A = 1f;
item.Modulate = modulate;
}
Color selfModulate = item.SelfModulate;
if (selfModulate.A < 1f)
{
selfModulate.A = 1f;
item.SelfModulate = selfModulate;
}
}
private static string DescribeCanvasItem(CanvasItem? item)
{
if (item == null || !GodotObject.IsInstanceValid(item))
{
return "null";
}
return $"{item.Name}(visible={item.Visible}, modA={item.Modulate.A:0.##}, selfA={item.SelfModulate.A:0.##}, z={item.ZIndex})";
}
private Node ResolveSpawnParent()
{
if (!SpawnParentPath.IsEmpty)
{
var customParent = GetNodeOrNull<Node>(SpawnParentPath);
if (customParent != null)
{
return customParent;
}
}
return GetParent() ?? this;
}
private Vector2 ResolveSpawnPosition(int index)
{
if (UseExplicitSpawnOffsets && index < SpawnOffsets.Count)
{
return GlobalPosition + SpawnOffsets[index];
}
if (UseExplicitSpawnOffsets && SpawnOffsets.Count > 0)
{
return GlobalPosition + SpawnOffsets[index % SpawnOffsets.Count];
}
if (EnableSmartSpawnPlacement && !Engine.IsEditorHint() && IsInsideTree())
{
return FindClearSpawnPosition();
}
float x = _rng.RandfRange(-SpawnAreaExtents.X, SpawnAreaExtents.X);
float y = _rng.RandfRange(-SpawnAreaExtents.Y, SpawnAreaExtents.Y);
return GlobalPosition + new Vector2(x, y);
}
private Vector2 FindClearSpawnPosition()
{
var spaceState = GetWorld2D().DirectSpaceState;
Vector2 fallback = GlobalPosition;
for (int attempt = 0; attempt < MaxSpawnAttempts; attempt++)
{
float x = _rng.RandfRange(-SpawnAreaExtents.X, SpawnAreaExtents.X);
float y = _rng.RandfRange(-SpawnAreaExtents.Y, SpawnAreaExtents.Y);
Vector2 candidate = GlobalPosition + new Vector2(x, y);
if (attempt == 0)
{
fallback = candidate;
}
if (IsPositionClear(spaceState, candidate))
{
if (LogSpawnEffectPositions && attempt > 0)
{
GD.Print($"[{Name}] 智能落点:第 {attempt + 1} 次尝试找到空闲位置 {candidate}");
}
return candidate;
}
}
if (LogSpawnEffectPositions)
{
GD.PushWarning($"[{Name}] 智能落点:{MaxSpawnAttempts} 次尝试均有障碍物,使用第一次候选点 {fallback}");
}
return fallback;
}
private bool IsPositionClear(PhysicsDirectSpaceState2D spaceState, Vector2 position)
{
_spawnCheckShape ??= new CircleShape2D();
_spawnCheckShape.Radius = SpawnCheckRadius;
var query = new PhysicsShapeQueryParameters2D
{
Shape = _spawnCheckShape,
Transform = new Transform2D(0f, position),
CollisionMask = ObstacleCheckMask,
CollideWithBodies = true,
CollideWithAreas = false,
};
var results = spaceState.IntersectShape(query, 1);
return results.Count == 0;
}
private void OnTriggerBodyEntered(Node2D body)
{
if (!string.IsNullOrWhiteSpace(TriggerGroupName) && !body.IsInGroup(TriggerGroupName))
{
GD.Print($"[{Name}] Trigger ignored: {body.Name} is not in group '{TriggerGroupName}'");
return;
}
GD.Print($"[{Name}] Trigger entered by: {body.Name}");
StartSpawnSequence();
}
private void EnsureTriggerArea()
{
if (TriggerArea == null || !GodotObject.IsInstanceValid(TriggerArea))
{
TriggerArea = GetNodeOrNull<Area2D>("TriggerArea");
_triggerAreaAutoCreated = false;
}
if (TriggerArea == null || !GodotObject.IsInstanceValid(TriggerArea))
{
TriggerArea = new Area2D
{
Name = "TriggerArea",
Monitoring = true,
Monitorable = false
};
AddChild(TriggerArea);
_triggerAreaAutoCreated = true;
if (Engine.IsEditorHint())
{
TriggerArea.Owner = GetTree().EditedSceneRoot;
}
}
bool shouldAutoConfigure = ShouldAutoConfigureTriggerArea();
if (!shouldAutoConfigure)
{
TriggerArea.Monitoring = true;
_triggerShape = TriggerArea.GetNodeOrNull<CollisionShape2D>("CollisionShape2D");
return;
}
TriggerArea.Position = TriggerOffset;
TriggerArea.CollisionLayer = TriggerCollisionLayer;
TriggerArea.CollisionMask = TriggerCollisionMask;
TriggerArea.Monitoring = true;
_triggerShape = TriggerArea.GetNodeOrNull<CollisionShape2D>("CollisionShape2D");
if (_triggerShape == null)
{
_triggerShape = new CollisionShape2D
{
Name = "CollisionShape2D"
};
TriggerArea.AddChild(_triggerShape);
if (Engine.IsEditorHint())
{
_triggerShape.Owner = GetTree().EditedSceneRoot;
}
}
}
private void UpdateTriggerAreaShape()
{
if (!ShouldAutoConfigureTriggerArea())
{
return;
}
if (_triggerShape == null)
{
return;
}
if (_triggerShape.Shape is not RectangleShape2D rectangle)
{
rectangle = new RectangleShape2D();
_triggerShape.Shape = rectangle;
}
rectangle.Size = new Vector2(Mathf.Max(1f, TriggerSize.X), Mathf.Max(1f, TriggerSize.Y));
_triggerShape.Position = Vector2.Zero;
_triggerShape.Disabled = false;
}
private SpawnEffectRefs PlaySpawnEffects(Vector2 spawnPosition)
{
SpawnEffectRefs effectRefs = new();
Vector2 backEffectPos = spawnPosition + SpawnBackEffectOffset;
Vector2 frontEffectPos = spawnPosition + SpawnFrontEffectOffset;
if (LogSpawnEffectPositions)
{
GD.Print($"[{Name}] SpawnFX base={spawnPosition}, backOffset={SpawnBackEffectOffset}, backPos={backEffectPos}, frontOffset={SpawnFrontEffectOffset}, frontPos={frontEffectPos}");
}
PackedScene? backScene = SpawnBackEffectScene ?? _runtimeBackEffectScene;
PackedScene? frontScene = SpawnFrontEffectScene ?? _runtimeFrontEffectScene;
var backEffectInstance = SpawnEffect(backScene, backEffectPos);
var frontEffectInstance = SpawnEffect(frontScene, frontEffectPos);
effectRefs.BackEffect = backEffectInstance?.Root;
effectRefs.BackAnimatedSprite = backEffectInstance?.AnimatedSprite;
effectRefs.BackEffectInstance = backEffectInstance;
effectRefs.FrontEffect = frontEffectInstance?.Root;
return effectRefs;
}
private SpawnEffectInstance? SpawnEffect(PackedScene? effectScene, Vector2 spawnPosition)
{
if (effectScene == null)
{
return null;
}
var instance = effectScene.Instantiate();
if (instance == null)
{
return null;
}
var effectInstance = new SpawnEffectInstance
{
Root = instance as Node2D
};
var parent = ResolveSpawnParent();
parent.AddChild(instance);
if (instance is Node2D node2D)
{
node2D.GlobalPosition = spawnPosition;
// 保留出生特效自身场景里的排序设置,不在生成器里强制修改 Z。
node2D.Visible = true;
}
AnimatedSprite2D? animatedSprite = instance as AnimatedSprite2D;
if (animatedSprite == null)
{
foreach (Node child in instance.FindChildren("*", "AnimatedSprite2D", true, false))
{
if (child is AnimatedSprite2D foundSprite)
{
animatedSprite = foundSprite;
break;
}
}
}
if (animatedSprite != null)
{
var animationName = animatedSprite.Animation;
if (!string.IsNullOrEmpty(animationName.ToString()) && animatedSprite.SpriteFrames != null)
{
animatedSprite.Visible = true;
animatedSprite.Frame = 0;
animatedSprite.FrameProgress = 0f;
animatedSprite.SpeedScale = 1f;
animatedSprite.SpriteFrames.SetAnimationLoop(animationName, false);
animatedSprite.Play(animationName);
if (LogSpawnEffectPositions)
{
GD.Print($"[{Name}] Spawn FX started: scene={effectScene.ResourcePath}, anim={animationName}, pos={spawnPosition}, z={animatedSprite.ZIndex}, frames={animatedSprite.SpriteFrames.GetFrameCount(animationName)}");
}
animatedSprite.AnimationFinished += () =>
{
effectInstance.Finished = true;
if (GodotObject.IsInstanceValid(instance))
{
instance.QueueFree();
}
};
return effectInstance;
}
GD.PushWarning($"{Name}: Spawn FX found AnimatedSprite2D but animation is invalid. scene={effectScene.ResourcePath}, anim={animationName}");
}
else
{
GD.PushWarning($"{Name}: Spawn FX scene does not contain AnimatedSprite2D. scene={effectScene.ResourcePath}");
}
effectInstance.AnimatedSprite = animatedSprite;
var timer = GetTree().CreateTimer(Mathf.Max(EnemyAppearDelay, 0.5f));
timer.Timeout += () =>
{
if (GodotObject.IsInstanceValid(instance))
{
instance.QueueFree();
}
};
return effectInstance;
}
private async System.Threading.Tasks.Task WaitForEnemyAppearGateAsync(SpawnEffectInstance? backEffectInstance)
{
switch (EnemyAppearGateMode)
{
case BackEffectSpawnGateMode.BackEffectFrame:
if (await WaitForBackEffectFrameAsync(backEffectInstance))
{
return;
}
break;
case BackEffectSpawnGateMode.BackEffectFinished:
if (await WaitForBackEffectFinishedAsync(backEffectInstance))
{
return;
}
break;
default:
break;
}
if (EnemyAppearGateMode == BackEffectSpawnGateMode.Delay || FallbackToDelayWhenGateUnavailable)
{
await WaitSecondsAsync(EnemyAppearDelay);
}
}
private async System.Threading.Tasks.Task<bool> WaitForBackEffectFrameAsync(SpawnEffectInstance? backEffectInstance)
{
AnimatedSprite2D? backAnimatedSprite = backEffectInstance?.AnimatedSprite;
if (!GodotObject.IsInstanceValid(backAnimatedSprite) || backAnimatedSprite == null)
{
return false;
}
int targetFrame = Mathf.Max(0, BackEffectAppearFrame);
var animationName = backAnimatedSprite.Animation;
if (backAnimatedSprite.SpriteFrames != null && !string.IsNullOrEmpty(animationName.ToString()))
{
int frameCount = backAnimatedSprite.SpriteFrames.GetFrameCount(animationName);
if (frameCount > 0)
{
targetFrame = Mathf.Clamp(targetFrame, 0, frameCount - 1);
}
}
double timeout = Mathf.Max(0f, BackEffectGateTimeout);
double start = Time.GetTicksMsec() / 1000.0;
while (GodotObject.IsInstanceValid(backAnimatedSprite))
{
if (backEffectInstance?.Finished == true)
{
return true;
}
if (backAnimatedSprite.Frame >= targetFrame)
{
return true;
}
if (timeout > 0 && (Time.GetTicksMsec() / 1000.0 - start) >= timeout)
{
GD.PushWarning($"{Name}: WaitForBackEffectFrame timeout, frame={backAnimatedSprite.Frame}, target={targetFrame}");
return false;
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
return false;
}
private async System.Threading.Tasks.Task<bool> WaitForBackEffectFinishedAsync(SpawnEffectInstance? backEffectInstance)
{
AnimatedSprite2D? backAnimatedSprite = backEffectInstance?.AnimatedSprite;
if (!GodotObject.IsInstanceValid(backAnimatedSprite) || backAnimatedSprite == null)
{
return false;
}
if (backEffectInstance?.Finished == true || !backAnimatedSprite.IsPlaying())
{
return true;
}
double timeout = Mathf.Max(0f, BackEffectGateTimeout);
double start = Time.GetTicksMsec() / 1000.0;
while (GodotObject.IsInstanceValid(backAnimatedSprite))
{
if (backEffectInstance?.Finished == true || !backAnimatedSprite.IsPlaying())
{
return true;
}
if (timeout > 0 && (Time.GetTicksMsec() / 1000.0 - start) >= timeout)
{
GD.PushWarning($"{Name}: WaitForBackEffectFinished timeout.");
return false;
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
return backEffectInstance?.Finished == true;
}
private async System.Threading.Tasks.Task WaitSecondsAsync(float seconds)
{
float waitSeconds = Mathf.Max(0f, seconds);
if (waitSeconds <= 0f)
{
return;
}
var timer = GetTree().CreateTimer(waitSeconds);
await ToSignal(timer, SceneTreeTimer.SignalName.Timeout);
}
private async void LowerFrontEffectAfterEnemySpawn(Node2D? frontEffectNode, Node enemy)
{
if (frontEffectNode == null || !GodotObject.IsInstanceValid(frontEffectNode))
{
return;
}
if (enemy is not Node2D enemyNode || !GodotObject.IsInstanceValid(enemyNode))
{
return;
}
float delay = Mathf.Max(0f, FrontEffectLowerDelay);
if (delay > 0f)
{
var timer = GetTree().CreateTimer(delay);
await ToSignal(timer, SceneTreeTimer.SignalName.Timeout);
}
if (!GodotObject.IsInstanceValid(frontEffectNode) || !GodotObject.IsInstanceValid(enemyNode))
{
return;
}
frontEffectNode.ZAsRelative = false;
frontEffectNode.ZIndex = enemyNode.ZIndex + FrontEffectPostSpawnZOffset;
if (LogSpawnEffectPositions)
{
GD.Print($"[{Name}] Front FX lowered after spawn: enemyZ={enemyNode.ZIndex}, frontFXZ={frontEffectNode.ZIndex}, offset={FrontEffectPostSpawnZOffset}, delay={delay:0.###}s");
}
}
private sealed class SpawnEffectRefs
{
public Node2D? BackEffect;
public AnimatedSprite2D? BackAnimatedSprite;
public SpawnEffectInstance? BackEffectInstance;
public Node2D? FrontEffect;
}
private sealed class SpawnEffectInstance
{
public Node2D? Root;
public AnimatedSprite2D? AnimatedSprite;
public bool Finished;
}
private bool ShouldDrawDebugOverlay()
{
if (!ShowDebugOverlay)
{
return false;