-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatchFlowController.cs
More file actions
2445 lines (2118 loc) · 100 KB
/
Copy pathMatchFlowController.cs
File metadata and controls
2445 lines (2118 loc) · 100 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
// MatchFlowController.cs — One-shot match loop driver.
using System;
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
namespace SoccerBot
{
public class MatchFlowController : MonoBehaviour
{
public enum Phase { Idle, Setup, Pass, Recovery, Possession, Shot, Score, Cooldown }
public event Action<Phase> PhaseChanged;
public event Action<Vector3, Vector3, float> PassStarted;
public event Action<float, float, bool> ReceiveResolved;
public event Action RecoveryTriggered;
public event Action<bool> RecoveryResolved;
public event Action<float, Vector3> ShotAttempted;
public event Action<FootContactData> FootContactRecorded;
public event Action<Scenario, string> RoundResolved;
[Header("Scene References")]
[SerializeField] private Transform _robotTransform;
[SerializeField] private Transform _playerTransform;
[SerializeField] private Transform _teammateTransform;
[SerializeField] private Transform _opponentTransform;
[SerializeField] private BallController _ball;
[SerializeField] private FPSPlayerController _player;
[SerializeField] private ScenarioTrigger _scenarioTrigger;
[SerializeField] private ScenarioPlayer _scenarioPlayer;
[SerializeField] private Transform _fpsCamera;
[SerializeField] private Transform _fpsAnchor;
[SerializeField] private ScorePanel _scorePanel;
[SerializeField] private ScoreBoard _scoreBoard;
[SerializeField] private GameObject _hudRoot;
[SerializeField] private ReceptionPromptPresenter _receptionPrompt;
[SerializeField] private ReceptionTargetIndicator _receptionTargetIndicator;
[SerializeField] private FieldAIController _fieldAI;
[Header("Ball Offsets")]
[SerializeField] private Vector3 _ballOffsetRobot = new(0f, 1.0f, 0.4f);
[SerializeField] private Vector3 _ballOffsetPlayer = new(0f, 0.3f, 0.6f);
[SerializeField] private float _passApex = 2.2f;
[Header("NPC Setup Stance (Player local-space)")]
[SerializeField] private Vector3 _teammateSetupOffset = new(-1.5f, 0f, 1.5f);
[SerializeField] private Vector3 _opponentSetupOffset = new(1.5f, 0f, 1.5f);
[Header("Timing (seconds)")]
[SerializeField] private float _setupDuration = 2.0f;
[SerializeField] private float _passFlightTime = 1.6f;
[SerializeField] private float _cooldownDuration = 3.0f;
[Header("Reception")]
[SerializeField, Range(0f, 1f)] private float _receiveWindowStart01 = 0.55f;
[SerializeField, Range(0f, 1f)] private float _receivePerfect01 = 0.78f;
[SerializeField, Range(0f, 1f)] private float _receiveWindowEnd01 = 0.95f;
[SerializeField, Range(1f, 90f)] private float _receiveFacingFullScoreAngle = 12f;
[SerializeField, Range(1f, 140f)] private float _receiveFacingFailAngle = 65f;
[SerializeField, Range(0f, 1f)] private float _minimumPossessionReceiveQuality = 0.20f;
[SerializeField, Range(0f, 0.4f)] private float _receivePowerBonus = 0.18f;
[SerializeField, Range(0f, 0.4f)] private float _poorReceivePowerPenalty = 0.12f;
[Header("Foot Contacts")]
[SerializeField] private bool _acceptFootContacts = true;
[SerializeField] private bool _requireRightTriggerForFootShot = true;
[SerializeField] private float _footReceivePerfectSpeed = 0.45f;
[SerializeField] private float _footReceiveFailSpeed = 2.8f;
[SerializeField, Range(0f, 1f)] private float _minimumFootShotPower = 0.12f;
[SerializeField, Range(0f, 1f)] private float _footShotSwingDirectionWeight = 0.65f;
[SerializeField, Range(0f, 0.5f)] private float _footShotLift = 0.08f;
[SerializeField] private bool _enableInstepShotAssist = true;
[SerializeField, Range(0f, 0.6f)] private float _instepShotAssistMax = 0.28f;
[SerializeField, Range(0f, 1f)] private float _instepShotAssistMinPower = 0.18f;
[SerializeField, Range(0f, 1f)] private float _instepShotAssistFullPower = 0.72f;
[SerializeField, Range(5f, 120f)] private float _instepShotAssistMaxAngle = 72f;
[Header("Player Pass / Shot Resolution")]
[SerializeField] private bool _enableTeammatePassByAim = true;
[SerializeField, Range(-1f, 1f)] private float _teammatePassAimDot = 0.82f;
[SerializeField] private float _teammatePassArrivalRadius = 1.15f;
[SerializeField, Range(0f, 1f)] private float _teammatePassSlowPower = 0.34f;
[SerializeField, Range(0f, 1f)] private float _teammatePassFastPower = 0.84f;
[SerializeField, Range(0f, 1f)] private float _teammatePassGoodScoreChance = 0.62f;
[Header("Recovery Mash")]
[SerializeField] private bool _enableRecoveryMash = true;
[SerializeField, Range(0.8f, 5f)] private float _recoveryDuration = 2.4f;
[SerializeField, Range(4, 40)] private int _recoveryPressTarget = 14;
[SerializeField, Range(0.03f, 0.5f)] private float _recoveryPushPerPress = 0.14f;
[SerializeField, Range(0f, 1.5f)] private float _recoveryHeldPush = 0.36f;
[SerializeField, Range(0.5f, 12f)] private float _recoveryOpponentLerpSpeed = 8f;
[SerializeField, Range(0.5f, 4f)] private float _recoverySuccessKnockback = 1.9f;
[SerializeField, Range(0.2f, 3f)] private float _recoveryFailSurgeDistance = 0.9f;
[SerializeField, Range(0f, 0.15f)] private float _recoveryShakeAmplitude = 0.035f;
[SerializeField, Range(4f, 60f)] private float _recoveryShakeFrequency = 32f;
[Header("Power Routing")]
[SerializeField, Range(0f, 0.3f)] private float _randomJitter = 0.10f;
[Header("Teammate Shot Targets (world space)")]
[SerializeField] private Transform _goalTargetIn;
[SerializeField] private Transform _goalTargetMiss;
[SerializeField] private Vector3 _goalTargetInPos = new(0f, 0.8f, 8.9f);
[SerializeField] private Vector3 _goalTargetMissPos = new(3.5f, 0.5f, 8.6f);
[Header("Goal / Field Boundary")]
[SerializeField] private FieldBuilder _fieldBuilder;
[SerializeField] private bool _ensureMatchBoundaryWalls = true;
[SerializeField] private bool _showMatchBoundaryWalls = false;
[SerializeField] private float _matchBoundaryPadding = 0.45f;
[SerializeField] private float _matchBoundaryWallHeight = 1.8f;
[SerializeField] private float _matchBoundaryWallThickness = 0.14f;
[SerializeField] private float _ballOutOfBoundsMargin = 0.25f;
[SerializeField] private float _ballFallY = -0.75f;
[SerializeField] private float _opponentGoalWidth = 3.5f;
[SerializeField] private float _opponentGoalHeight = 1.55f;
[SerializeField] private float _opponentGoalDepth = 0.6f;
[SerializeField] private float _goalMouthBoundaryGapPadding = 0.35f;
[Header("Teammate Shot Animation")]
[SerializeField] private float _shotPassToTeammate = 0.6f;
[SerializeField] private float _teammateAimDuration = 0.5f;
[SerializeField] private float _teammateAimHold = 0.5f;
[SerializeField] private float _shotFlightTime = 1.4f;
[SerializeField] private float _shotApex = 2.5f;
[SerializeField] private float _teammateRunDistance = 2.0f;
[SerializeField] private float _teammateRunFraction = 0.3f;
[SerializeField] private float _resultHoldDelay = 0.6f;
[Header("NPC Reactions")]
[SerializeField] private bool _opponentTracksBall = true;
[SerializeField, Range(1f, 10f)] private float _opponentLookSpeed = 4f;
[SerializeField] private bool _teammateCelebrates = true;
[Header("Demo Scene Polish")]
[SerializeField] private bool _enableDemoScenePolish = true;
[SerializeField] private bool _replaceRobotWithTeammateVisual = true;
[Tooltip("Global down-scale applied to scene-authored NPCs (1 = original size).")]
[SerializeField] private float _npcScaleMultiplier = 0.8f;
[Tooltip("Vertical nudge for the FPS eye height (metres, negative = lower view).")]
[SerializeField] private float _eyeHeightAdjust = -0.25f;
[SerializeField] private Vector3 _robotDemoPosition = new(-2.4f, 0f, -3.6f);
[SerializeField] private Vector3 _robotVisualLocalOffset = Vector3.zero;
[SerializeField] private Vector3 _robotVisualLocalScale = Vector3.one * 0.576f;
[SerializeField] private Vector3 _goalkeeperPosition = new(0f, 0f, 8.15f);
[SerializeField] private Vector3 _goalkeeperLookAt = new(0f, 0f, 2f);
[SerializeField] private Vector3[] _blueBackgroundNpcPositions =
{
new(-2.2f, 0f, 5.8f)
};
[SerializeField] private Vector3[] _redBackgroundNpcPositions =
{
new(2.4f, 0f, 6.9f)
};
[SerializeField] private float _supportNpcForwardDistance = 4.8f;
[SerializeField] private float _supportNpcBackDistance = 3.6f;
[SerializeField] private float _goalkeeperForwardDistance = 6.8f;
[SerializeField] private float _backgroundNpcScale = 0.56f;
[SerializeField] private float _goalkeeperScale = 0.64f;
[SerializeField] private float _lampHeadRuntimeZ = 0.24f;
[SerializeField] private Vector3 _goalkeeperGoalCenter = new(0f, 0.0055f, 8.15f);
[Header("Whistle")]
[SerializeField] private AudioSource _whistleSource;
[SerializeField] private AudioSource _ballReceiveSource;
[Header("Score Display Data")]
[SerializeField] private Scenario _scoreSuccessData;
[SerializeField] private Scenario _shotMissedData;
private Phase _currentPhase = Phase.Idle;
public Phase CurrentPhase
{
get => _currentPhase;
private set
{
if (_currentPhase == value)
return;
_currentPhase = value;
PhaseChanged?.Invoke(_currentPhase);
}
}
public enum BoundaryExitKind { Unknown, Sideline, GoalLine, Fall }
private Coroutine _loop;
private bool _isMatchRunning;
private InputAction _menuAction;
private MainMenuPanel _mainMenu;
private Transform _goalkeeperTransform;
private Transform _attackArrowTransform;
private TextMeshPro _attackArrowLabel;
private Canvas _fallbackHudCanvas;
private TextMeshProUGUI _fallbackHudArrowLabel;
private TextMeshProUGUI _fallbackHudStatusLabel;
private float _passProgress01;
private float _receiveQuality = 1f;
private bool _receiveAttempted;
private Vector3 _currentPassStart;
private Vector3 _currentPassEnd;
private RecoveryMashState _recoveryMash;
private Transform _recoveryShakeTarget;
private Vector3 _recoveryShakeBaseLocalPos;
private CanvasGroup _recoveryHudGroup;
private RectTransform _recoveryHudRoot;
private RectTransform _recoveryButtonRect;
private TextMeshProUGUI _recoveryPromptLabel;
private TextMeshProUGUI _recoveryMeterLabel;
private GameObject _matchBoundaryRoot;
private Coroutine _shotRoutine;
private bool _rallyResolved;
private bool _passJudgementActive;
private float _passJudgementPower01;
private float _passJudgementAimDot = 1f;
private float _passJudgementStartedAt = -999f;
private readonly System.Collections.Generic.List<Image> _recoveryBorderImages = new();
private readonly System.Collections.Generic.List<Transform> _backgroundNpcTransforms = new();
private static readonly Color BlueTeamColor = new(0.1f, 0.3f, 0.9f, 1f);
private static readonly Color RedTeamColor = new(0.9f, 0.1f, 0.1f, 1f);
void Start()
{
ApplyDemoOverrides();
AutoResolveRefs();
EnsureAICoachRuntime();
EnsureFarGoalTargets();
EnsureMatchBoundaryWalls();
EnsureDemoScenePolish();
EnsureFieldAIController();
if (_player != null)
{
_player.OnShoot += HandlePlayerShot;
_player.OnReceiveAttempt += HandleReceiveAttempt;
}
if (_scenarioPlayer != null) _scenarioPlayer.OnScenarioComplete += HandleScenarioComplete;
_menuAction = new InputAction("OpenMenu", InputActionType.Button);
_menuAction.AddBinding("<Keyboard>/escape");
_menuAction.AddBinding("<XRController>{LeftHand}/menuButton");
_menuAction.AddBinding("<XRController>{RightHand}/secondaryButton");
_menuAction.Enable();
ResetForMenu();
}
void OnDestroy()
{
if (_player != null)
{
_player.OnShoot -= HandlePlayerShot;
_player.OnReceiveAttempt -= HandleReceiveAttempt;
}
if (_scenarioPlayer != null) _scenarioPlayer.OnScenarioComplete -= HandleScenarioComplete;
if (_menuAction != null)
{
_menuAction.Disable();
_menuAction.Dispose();
_menuAction = null;
}
}
public void PrepareForMatchStart()
{
ResetForMenu();
_scoreBoard?.ResetCounts();
}
public void BeginMatch()
{
PrepareForMatchStart();
_isMatchRunning = true;
if (_hudRoot != null) _hudRoot.SetActive(true);
if (_mainMenu != null) _mainMenu.gameObject.SetActive(false);
if (_loop != null) StopCoroutine(_loop);
_loop = StartCoroutine(MatchLoop());
}
public void ResetForMenu()
{
_isMatchRunning = false;
if (_loop != null)
{
StopCoroutine(_loop);
_loop = null;
}
if (_shotRoutine != null)
{
StopCoroutine(_shotRoutine);
_shotRoutine = null;
}
CurrentPhase = Phase.Idle;
_rallyResolved = false;
ResetPassJudgement();
if (_player != null)
{
_player.ShootingEnabled = false;
_player.MovementEnabled = false;
_player.ReceptionEnabled = false;
}
ResetReceptionState(1f);
HideRecoveryHud();
RestoreRecoveryShakeTarget();
if (_hudRoot != null) _hudRoot.SetActive(false);
_receptionPrompt?.Hide();
_receptionTargetIndicator?.Hide();
_scorePanel?.HideImmediate();
if (_robotTransform != null) _robotTransform.gameObject.SetActive(true);
if (_teammateTransform != null) _teammateTransform.gameObject.SetActive(true);
if (_opponentTransform != null) _opponentTransform.gameObject.SetActive(true);
if (_ball != null && _robotTransform != null)
_ball.AttachTo(_robotTransform, _ballOffsetRobot);
}
void Update()
{
if (_menuAction == null || !_menuAction.WasPressedThisFrame())
{
UpdateAttackArrow();
GuardGoalAndBoundary();
}
else if (_mainMenu != null)
{
bool menuOpen = _mainMenu.gameObject.activeSelf && _mainMenu.gameObject.activeInHierarchy;
if (!menuOpen)
{
ResetForMenu();
_mainMenu.ShowMenu();
}
}
}
private void AutoResolveRefs()
{
if (_robotTransform == null)
{
var go = GameObject.Find("Robot");
if (go != null) _robotTransform = go.transform;
}
{
var go = GameObject.Find("Player");
if (go != null) _playerTransform = go.transform;
}
{
var go = GameObject.Find("Teammate");
if (go != null) _teammateTransform = go.transform;
}
if (_opponentTransform == null)
{
var go = GameObject.Find("Opponent");
if (go != null) _opponentTransform = go.transform;
}
if (_ball == null) _ball = FindFirstObjectByType<BallController>();
if (_fieldBuilder == null) _fieldBuilder = FindFirstObjectByType<FieldBuilder>(FindObjectsInactive.Include);
if (_playerTransform != null)
{
var pc = _playerTransform.GetComponent<FPSPlayerController>();
if (pc != null) _player = pc;
}
if (_player == null) _player = FindFirstObjectByType<FPSPlayerController>();
if (_scenarioTrigger == null) _scenarioTrigger = FindFirstObjectByType<ScenarioTrigger>();
if (_scenarioPlayer == null) _scenarioPlayer = FindFirstObjectByType<ScenarioPlayer>();
if (_opponentTransform == null && _scenarioPlayer != null)
_opponentTransform = _scenarioPlayer.OpponentTransform;
if (_teammateTransform == null && _scenarioPlayer != null)
_teammateTransform = _scenarioPlayer.TeammateTransform;
if (_playerTransform != null)
{
var t = _playerTransform.Find("FpsAnchor");
if (t != null) _fpsAnchor = t;
}
if (_teammateTransform != null)
{
_teammateSetupOffset = new Vector3(-2.2f, 0f, 2.6f);
}
if (_opponentTransform != null)
{
_opponentSetupOffset = new Vector3(2.0f, 0f, 3.2f);
}
if (_fpsAnchor != null)
{
var t = _fpsAnchor.Find("FpsCamera");
if (t != null) _fpsCamera = t;
}
if (_goalTargetIn == null)
{
var go = GameObject.Find("GoalTarget_In");
if (go != null) _goalTargetIn = go.transform;
}
if (_goalTargetMiss == null)
{
var go = GameObject.Find("GoalTarget_Miss");
if (go != null) _goalTargetMiss = go.transform;
}
if (_scorePanel == null) _scorePanel = FindFirstObjectByType<ScorePanel>(FindObjectsInactive.Include);
if (_scoreBoard == null) _scoreBoard = FindFirstObjectByType<ScoreBoard>(FindObjectsInactive.Include);
if (_hudRoot == null)
{
var hud = GameObject.Find("HUD");
if (hud != null) _hudRoot = hud;
}
if (_receptionPrompt == null)
_receptionPrompt = FindFirstObjectByType<ReceptionPromptPresenter>(FindObjectsInactive.Include);
if (_receptionPrompt == null)
_receptionPrompt = gameObject.AddComponent<ReceptionPromptPresenter>();
_receptionPrompt.Configure(_fpsCamera != null ? _fpsCamera : _fpsAnchor);
if (_receptionTargetIndicator == null)
_receptionTargetIndicator = FindFirstObjectByType<ReceptionTargetIndicator>(FindObjectsInactive.Include);
if (_receptionTargetIndicator == null)
{
var indicatorGo = new GameObject("ReceptionTargetIndicator");
_receptionTargetIndicator = indicatorGo.AddComponent<ReceptionTargetIndicator>();
}
_receptionTargetIndicator.Hide();
if (_mainMenu == null) _mainMenu = FindFirstObjectByType<MainMenuPanel>(FindObjectsInactive.Include);
}
private void EnsureAICoachRuntime()
{
AICoachClient coachClient = FindAnyObjectByType<AICoachClient>(FindObjectsInactive.Include);
if (coachClient == null)
coachClient = gameObject.AddComponent<AICoachClient>();
GameEventRecorder recorder = FindAnyObjectByType<GameEventRecorder>(FindObjectsInactive.Include);
if (recorder == null)
recorder = gameObject.AddComponent<GameEventRecorder>();
recorder.Configure(this, _ball, _scorePanel, coachClient);
}
private void EnsureFieldAIController()
{
if (_fieldAI == null)
_fieldAI = FindFirstObjectByType<FieldAIController>(FindObjectsInactive.Include);
if (_fieldAI == null)
_fieldAI = gameObject.AddComponent<FieldAIController>();
_fieldAI.Configure(
this,
_ball,
_playerTransform,
_teammateTransform,
_opponentTransform,
_goalkeeperTransform);
}
private void PlayWhistle()
{
if (_whistleSource == null)
{
_whistleSource = gameObject.AddComponent<AudioSource>();
_whistleSource.playOnAwake = false;
_whistleSource.spatialBlend = 0f;
}
var clip = WhistleGenerator.Create();
_whistleSource.PlayOneShot(clip, 0.8f);
}
private void PlayBallReceive()
{
if (_ballReceiveSource == null)
{
_ballReceiveSource = gameObject.AddComponent<AudioSource>();
_ballReceiveSource.playOnAwake = false;
_ballReceiveSource.spatialBlend = 0f;
}
var clip = ThudGenerator.Create();
_ballReceiveSource.PlayOneShot(clip, 0.9f);
}
private void ApplyDemoOverrides()
{
_goalTargetInPos = new Vector3(1.1f, 0.75f, 8.9f);
_goalTargetMissPos = new Vector3(3.8f, 0.5f, 8.6f);
}
private Vector3 GetAttackForward()
{
if (_playerTransform != null)
{
Vector3 forward = _playerTransform.forward;
forward.y = 0f;
if (forward.sqrMagnitude > 0.001f)
return forward.normalized;
}
if (_playerTransform != null && _goalTargetIn != null)
{
Vector3 forward = _goalTargetIn.position - _playerTransform.position;
forward.y = 0f;
if (forward.sqrMagnitude > 0.001f)
return forward.normalized;
}
return Vector3.forward;
}
private Vector3 GetAttackRight()
{
Vector3 forward = GetAttackForward();
return new Vector3(forward.z, 0f, -forward.x).normalized;
}
private static bool UseQuestPromptText()
{
return Application.platform == RuntimePlatform.Android;
}
private void EnsureFarGoalTargets()
{
if (_goalTargetIn == null)
{
var go = new GameObject("GoalTarget_In");
go.transform.position = _goalTargetInPos;
_goalTargetIn = go.transform;
}
else
{
_goalTargetIn.position = _goalTargetInPos;
}
if (_goalTargetMiss == null)
{
var go = new GameObject("GoalTarget_Miss");
go.transform.position = _goalTargetMissPos;
_goalTargetMiss = go.transform;
}
else
{
_goalTargetMiss.position = _goalTargetMissPos;
}
}
private void EnsureMatchBoundaryWalls()
{
if (!_ensureMatchBoundaryWalls)
return;
if (_fieldBuilder == null)
_fieldBuilder = FindFirstObjectByType<FieldBuilder>(FindObjectsInactive.Include);
Vector3 center = _fieldBuilder != null ? _fieldBuilder.transform.position : Vector3.zero;
Quaternion rotation = _fieldBuilder != null ? _fieldBuilder.transform.rotation : Quaternion.identity;
float width = GetFieldHalfWidth() * 2f + _matchBoundaryPadding * 2f;
float length = GetFieldHalfLength() * 2f + _matchBoundaryPadding * 2f;
float thickness = Mathf.Max(0.02f, _matchBoundaryWallThickness);
float height = Mathf.Max(0.2f, _matchBoundaryWallHeight);
if (_matchBoundaryRoot == null)
_matchBoundaryRoot = new GameObject("MatchFlowBoundary");
center.y += height * 0.5f;
_matchBoundaryRoot.SetActive(true);
_matchBoundaryRoot.transform.SetPositionAndRotation(center, rotation);
DisableLegacyBoundaryWall("BackWall");
DisableLegacyBoundaryWall("FrontWall");
EnsureGoalLineBoundaryWalls("BackWall", -length * 0.5f, width, height, thickness);
EnsureGoalLineBoundaryWalls("FrontWall", length * 0.5f, width, height, thickness);
EnsureMatchBoundaryWall("LeftWall", new Vector3(-width * 0.5f, 0f, 0f), new Vector3(thickness, height, length), BoundaryExitKind.Sideline);
EnsureMatchBoundaryWall("RightWall", new Vector3(width * 0.5f, 0f, 0f), new Vector3(thickness, height, length), BoundaryExitKind.Sideline);
EnsureOpponentGoalTrigger(height);
}
private void EnsureGoalLineBoundaryWalls(string prefix, float localZ, float width, float height, float thickness)
{
float gapWidth = Mathf.Clamp(
_opponentGoalWidth + _goalMouthBoundaryGapPadding * 2f,
0f,
Mathf.Max(0f, width - thickness * 4f));
float segmentWidth = Mathf.Max(0.02f, (width - gapWidth) * 0.5f);
float centerOffset = gapWidth * 0.5f + segmentWidth * 0.5f;
EnsureMatchBoundaryWall(
$"{prefix}Left",
new Vector3(-centerOffset, 0f, localZ),
new Vector3(segmentWidth, height, thickness),
BoundaryExitKind.GoalLine);
EnsureMatchBoundaryWall(
$"{prefix}Right",
new Vector3(centerOffset, 0f, localZ),
new Vector3(segmentWidth, height, thickness),
BoundaryExitKind.GoalLine);
}
private void DisableLegacyBoundaryWall(string wallName)
{
if (_matchBoundaryRoot == null)
return;
Transform wall = _matchBoundaryRoot.transform.Find(wallName);
if (wall != null)
wall.gameObject.SetActive(false);
}
private void EnsureMatchBoundaryWall(string wallName, Vector3 localPosition, Vector3 localScale, BoundaryExitKind exitKind)
{
Transform wall = _matchBoundaryRoot.transform.Find(wallName);
if (wall == null)
{
GameObject wallGo = GameObject.CreatePrimitive(PrimitiveType.Cube);
wallGo.name = wallName;
wallGo.layer = 2;
wallGo.transform.SetParent(_matchBoundaryRoot.transform, false);
var reporter = wallGo.GetComponent<MatchBoundaryWall>();
if (reporter == null)
reporter = wallGo.AddComponent<MatchBoundaryWall>();
reporter.Configure(this, exitKind);
Renderer renderer = wallGo.GetComponent<Renderer>();
if (renderer != null)
{
renderer.material.color = new Color(0.08f, 0.22f, 0.35f, 0.35f);
renderer.enabled = _showMatchBoundaryWalls;
}
wall = wallGo.transform;
}
else
{
var reporter = wall.GetComponent<MatchBoundaryWall>();
if (reporter == null)
reporter = wall.gameObject.AddComponent<MatchBoundaryWall>();
reporter.Configure(this, exitKind);
}
if (wall == null)
{
Debug.LogWarning($"[MatchFlow] Boundary wall '{wallName}' could not be created.");
return;
}
wall.localPosition = localPosition;
wall.localRotation = Quaternion.identity;
wall.localScale = localScale;
Renderer existingRenderer = wall.GetComponent<Renderer>();
if (existingRenderer != null)
existingRenderer.enabled = _showMatchBoundaryWalls;
}
private void EnsureOpponentGoalTrigger(float boundaryHeight)
{
if (_matchBoundaryRoot == null)
return;
Transform trigger = _matchBoundaryRoot.transform.Find("OpponentGoalTrigger");
if (trigger == null)
{
GameObject triggerGo = new GameObject("OpponentGoalTrigger", typeof(BoxCollider), typeof(MatchGoalTrigger));
triggerGo.layer = 2;
triggerGo.transform.SetParent(_matchBoundaryRoot.transform, false);
trigger = triggerGo.transform;
}
float halfLength = GetFieldHalfLength();
float goalDepth = Mathf.Max(0.05f, _opponentGoalDepth);
float goalHeight = Mathf.Max(0.1f, _opponentGoalHeight);
float triggerDepth = goalDepth * 2f + _ballOutOfBoundsMargin;
float centerZ = halfLength + _ballOutOfBoundsMargin * 0.5f;
float centerY = (goalHeight - Mathf.Max(0.2f, boundaryHeight)) * 0.5f;
trigger.gameObject.SetActive(true);
trigger.localPosition = new Vector3(0f, centerY, centerZ);
trigger.localRotation = Quaternion.identity;
trigger.localScale = Vector3.one;
BoxCollider collider = trigger.GetComponent<BoxCollider>();
collider.isTrigger = true;
collider.center = Vector3.zero;
collider.size = new Vector3(
Mathf.Max(0.1f, _opponentGoalWidth),
goalHeight,
Mathf.Max(0.1f, triggerDepth));
MatchGoalTrigger reporter = trigger.GetComponent<MatchGoalTrigger>();
reporter.Configure(this);
}
private void EnsureDemoScenePolish()
{
if (!_enableDemoScenePolish) return;
EnsureAtmosphereControllers();
EnsureRobotVisualSwap();
EnsureGoalkeeper();
EnsureBackgroundNpcs();
EnsureAttackArrow();
EnsureFallbackHud();
ApplyNpcDownscale();
ApplyEyeHeight();
}
private void EnsureAtmosphereControllers()
{
if (FindFirstObjectByType<WeatherController>(FindObjectsInactive.Include) == null)
gameObject.AddComponent<WeatherController>();
var lighting = FindFirstObjectByType<LightingConfigurator>(FindObjectsInactive.Include);
if (lighting != null)
lighting.Apply();
}
// Lowers (or raises) the FPS eye height by a fixed nudge, once.
private bool _eyeHeightApplied;
private void ApplyEyeHeight()
{
if (_eyeHeightApplied || Mathf.Approximately(_eyeHeightAdjust, 0f)) return;
if (_fpsAnchor == null) return;
_eyeHeightApplied = true;
Vector3 p = _fpsAnchor.localPosition;
p.y += _eyeHeightAdjust;
_fpsAnchor.localPosition = p;
}
// Down-scales the scene-authored NPCs (the runtime-spawned robot /
// goalkeeper / support NPCs are already scaled at creation time).
// The ball keeps its authored scale because its visible mesh already
// matches the collision/trajectory offsets.
// Guarded so it only ever runs once, even if polish is re-invoked.
private bool _npcDownscaleApplied;
private void ApplyNpcDownscale()
{
if (_npcDownscaleApplied || Mathf.Approximately(_npcScaleMultiplier, 1f)) return;
_npcDownscaleApplied = true;
ScaleTransform(_teammateTransform);
ScaleTransform(_opponentTransform);
}
private void ScaleTransform(Transform t)
{
if (t == null) return;
t.localScale *= _npcScaleMultiplier;
}
private void EnsureRobotVisualSwap()
{
if (!_replaceRobotWithTeammateVisual || _robotTransform == null) return;
_robotTransform.position = _robotDemoPosition;
_robotTransform.rotation = Quaternion.LookRotation(Vector3.forward);
var builder = _robotTransform.GetComponent<CharacterBuilder>();
if (builder != null) builder.enabled = false;
Transform existingModel = _robotTransform.Find("Model");
if (existingModel != null)
{
existingModel.localPosition = _robotVisualLocalOffset;
existingModel.localRotation = Quaternion.identity;
existingModel.localScale = _robotVisualLocalScale * _npcScaleMultiplier;
TintRenderers(existingModel.gameObject, BlueTeamColor);
return;
}
Transform sourceModel = FindVisualTemplate(_teammateTransform);
if (sourceModel == null) sourceModel = FindVisualTemplate(_opponentTransform);
if (sourceModel == null) return;
var model = Instantiate(sourceModel.gameObject, _robotTransform);
model.name = "Model";
model.transform.localPosition = _robotVisualLocalOffset;
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = _robotVisualLocalScale * _npcScaleMultiplier;
TintRenderers(model, BlueTeamColor);
}
private void EnsureGoalkeeper()
{
Vector3 forward = GetAttackForward();
_goalkeeperPosition = _goalkeeperGoalCenter;
_goalkeeperLookAt = _goalkeeperGoalCenter - forward * _goalkeeperForwardDistance;
_goalkeeperLookAt.y = _goalkeeperGoalCenter.y;
var existing = GameObject.Find("Goalkeeper");
if (existing != null)
{
_goalkeeperTransform = existing.transform;
}
else if (_goalkeeperTransform == null)
{
_goalkeeperTransform = CreateNpcFromPrefab(
"Goalkeeper",
"strong man b",
_goalkeeperPosition,
RedTeamColor,
Vector3.one * (_goalkeeperScale * _npcScaleMultiplier));
}
if (_goalkeeperTransform == null) return;
_goalkeeperTransform.gameObject.SetActive(true);
_goalkeeperTransform.position = _goalkeeperPosition;
Vector3 toLook = _goalkeeperLookAt - _goalkeeperTransform.position;
toLook.y = 0f;
if (toLook.sqrMagnitude > 0.001f)
_goalkeeperTransform.rotation = Quaternion.LookRotation(toLook);
}
private void EnsureBackgroundNpcs()
{
if (_backgroundNpcTransforms.Count == 0)
{
SpawnBackgroundNpcSet("BlueSupport", "normal man a", _blueBackgroundNpcPositions, BlueTeamColor);
SpawnBackgroundNpcSet("RedSupport", "normal woman b", _redBackgroundNpcPositions, RedTeamColor);
}
Vector3 forward = GetAttackForward();
Vector3 right = GetAttackRight();
Vector3 center = (_playerTransform != null ? _playerTransform.position : Vector3.zero) - forward * _supportNpcBackDistance;
center.y = 0f;
for (int i = 0; i < _backgroundNpcTransforms.Count; i++)
{
Transform npc = _backgroundNpcTransforms[i];
if (npc == null) continue;
float side = i % 2 == 0 ? -1f : 1f;
float depth = i < 2 ? 0f : -1.2f;
npc.position = center + right * side * 2.6f + forward * depth;
Vector3 toLook = (_playerTransform != null ? _playerTransform.position : _goalkeeperLookAt) - npc.position;
toLook.y = 0f;
if (toLook.sqrMagnitude > 0.001f)
npc.rotation = Quaternion.LookRotation(toLook);
}
}
private void SpawnBackgroundNpcSet(string prefix, string prefabName, Vector3[] positions, Color color)
{
if (positions == null) return;
for (int i = 0; i < positions.Length; i++)
{
var npc = CreateNpcFromPrefab(
$"{prefix}_{i + 1}",
prefabName,
positions[i],
color,
Vector3.one * (_backgroundNpcScale * _npcScaleMultiplier));
if (npc == null) continue;
Vector3 toLook = _goalkeeperLookAt - npc.position;
toLook.y = 0f;
if (toLook.sqrMagnitude > 0.001f)
npc.rotation = Quaternion.LookRotation(toLook);
_backgroundNpcTransforms.Add(npc);
}
}
private Transform CreateNpcFromPrefab(string objectName, string prefabName, Vector3 position, Color color, Vector3 scale)
{
var existing = GameObject.Find(objectName);
if (existing != null) return existing.transform;
Transform sourceModel = ResolveNpcVisualTemplate(prefabName, color);
if (sourceModel == null) return null;
var root = new GameObject(objectName).transform;
root.position = position;
var model = Instantiate(sourceModel.gameObject, root);
model.name = "Model";
model.transform.localPosition = Vector3.zero;
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = scale;
TintRenderers(model, color);
return root;
}
private Transform ResolveNpcVisualTemplate(string prefabName, Color color)
{
Transform preferred = FindVisualTemplateByName(prefabName, _teammateTransform, _opponentTransform, _robotTransform);
if (preferred != null) return preferred;
bool useBlueSource = color == BlueTeamColor;
if (useBlueSource)
{
preferred = FindVisualTemplate(_teammateTransform);
if (preferred == null) preferred = FindVisualTemplate(_opponentTransform);
}
else
{
preferred = FindVisualTemplate(_opponentTransform);
if (preferred == null) preferred = FindVisualTemplate(_teammateTransform);
}
if (preferred != null) return preferred;
return FindVisualTemplate(_robotTransform);
}
private static Transform FindVisualTemplateByName(string prefabName, params Transform[] roots)
{
if (string.IsNullOrWhiteSpace(prefabName) || roots == null) return null;
string normalizedPrefabName = NormalizeVisualName(prefabName);
foreach (Transform root in roots)
{
if (root == null) continue;
foreach (Transform candidate in root.GetComponentsInChildren<Transform>(true))
{
if (NormalizeVisualName(candidate.name) != normalizedPrefabName) continue;
Transform template = FindVisualTemplate(candidate);
if (template != null) return template;
}
if (NormalizeVisualName(root.name) == normalizedPrefabName)
{
Transform template = FindVisualTemplate(root);
if (template != null) return template;
}
}
return null;
}
private static string NormalizeVisualName(string value)
{
if (string.IsNullOrWhiteSpace(value)) return string.Empty;
return value.Replace("-", string.Empty).Replace("_", string.Empty).Replace(" ", string.Empty).ToLowerInvariant();
}
private static void TintRenderers(GameObject root, Color color)
{
foreach (var renderer in root.GetComponentsInChildren<Renderer>())
{
var block = new MaterialPropertyBlock();
renderer.GetPropertyBlock(block);
block.SetColor("_BaseColor", color);
renderer.SetPropertyBlock(block);
}
}
private static Transform FindVisualTemplate(Transform root)
{
if (root == null) return null;
var directModel = root.Find("Model");
if (directModel != null) return directModel;
foreach (Transform child in root)
{
if (child.GetComponentInChildren<Renderer>(true) != null)
return child;
}
return root.GetComponentInChildren<Renderer>(true) != null ? root : null;
}
private void EnsureAttackArrow()
{
if (_attackArrowTransform != null) return;
var root = new GameObject("AttackDirectionArrow").transform;
_attackArrowTransform = root;
root.localScale = Vector3.one * 0.08f;
var label = root.gameObject.AddComponent<TextMeshPro>();
label.text = "→";
label.fontSize = 12f;
label.alignment = TextAlignmentOptions.Center;
label.color = new Color(1f, 0.82f, 0.12f, 1f);
label.outlineWidth = 0.25f;
label.enableWordWrapping = false;
_attackArrowLabel = label;
UpdateAttackArrow();
}
private void UpdateAttackArrow()
{
if (_playerTransform == null) return;
bool showHud = _isMatchRunning && CurrentPhase != Phase.Idle;
if (_fallbackHudCanvas != null)
_fallbackHudCanvas.gameObject.SetActive(showHud);
if (_attackArrowTransform != null)
_attackArrowTransform.gameObject.SetActive(showHud);
if (!showHud) return;
Transform view = _fpsCamera != null ? _fpsCamera : _playerTransform;
Vector3 targetPos = _goalkeeperTransform != null ? _goalkeeperTransform.position : _goalkeeperGoalCenter;
Vector3 local = view.InverseTransformPoint(targetPos);
string horizontal = local.x > 0.35f ? "→" : local.x < -0.35f ? "←" : string.Empty;
string vertical = local.y > 0.2f ? "↑" : local.y < -0.15f ? "↓" : string.Empty;
string arrowText = string.IsNullOrEmpty(vertical + horizontal) ? "↑" : vertical + horizontal;