-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMABotAiComponentExample.cpp
More file actions
1735 lines (1588 loc) · 63.9 KB
/
Copy pathMABotAiComponentExample.cpp
File metadata and controls
1735 lines (1588 loc) · 63.9 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
/*
*
* Primary component for handling bot AI -- decision making, movement, aiming.
* General approach is to run DetermineCurrentTask every half second, which examines the game state and bot state to determine
* which action should be taken, who their target should be, and where they should move. DetermineCurrentTask uses a behavior weighting system to determine what action to perform.
*
* Bots are assigned positions relevant to gameplay on creation (Stay at home, chaser, offense, LO, route runner)
* and how they react is influenced by these positions.
*
* Opon the bot component actually ticking, it will do its best to carry out the actions decided upon via DetermineCurrentTask
*
* Further enhancements would involve a (much) more intelligent movement system, primarily to handle movement around/near base geometry, and a team coordinator that allows for
* better intra-bot communication for flag tossing and flag stand clearing.
*
*/
#include "MidairCE.h"
#include "MABotAIComponent.h"
#include "Perception/PawnSensingComponent.h"
#include "Player/AIPlayerController.h"
#include "Player/MACharacter.h"
#include "Game/CTF/MACTFFlag.h"
#include "Game/CTF/MACTFFlagBase.h"
#include "Kismet/KismetMathLibrary.h"
// Sets default values for this component's properties
UMABotAIComponent::UMABotAIComponent()
{
//turn off pawn sense stuff by default
PrimaryComponentTick.bCanEverTick = true;
}
void UMABotAIComponent::EnableBotAI()
{
//skip initialization if AI is already on
if (bBotInitialized)
{
return;
}
PawnSensingComp = NewObject<UPawnSensingComponent>(this, UPawnSensingComponent::StaticClass());
PrimaryComponentTick.bCanEverTick = true;
PawnSensingComp->OnSeePawn.AddDynamic(this, &UMABotAIComponent::OnPawnSeen);
PawnSensingComp->bOnlySensePlayers = false;
PawnSensingComp->SetSensingUpdatesEnabled(true);
PawnSensingComp->bSeePawns = true;
PawnSensingComp->bHearNoises = false;
PawnSensingComp->SightRadius = 60000.0f;
PawnSensingComp->RegisterComponent();
if (ParentCharacter != nullptr)
{
ParentCharacter->GetWorldTimerManager().SetTimer(TimerHandle_DetermineCurrentTask, this, &UMABotAIComponent::DetermineCurrentTask, 0.5f, true);
}
//initialize flag related game state
for (TActorIterator<AMACTFFlagBase> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
AMACTFFlagBase *Stand = *ActorItr;
uint8 BotTeamId = ParentCharacter->GetTeamId();
uint8 StandTeamId = Stand->GetTeamId();
bool bEnemyStand = BotTeamId != StandTeamId;
if (bEnemyStand)
{
GameState.EnemyStandLocation = Stand->GetActorLocation();
}
else {
GameState.FriendlyStandLocation = Stand->GetActorLocation();
}
}
AccuracyLevel = BotConfig.AccuracyLevel;
bBotInitialized = true;
}
// Called every frame
void UMABotAIComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (ParentCharacter == nullptr || ParentCharacter->GetController() == nullptr || bIsDead)
{
return;
}
//Guard against missing initialization upon bot creation
if (!bBotInitialized)
{
AAIPlayerController* AIPC = Cast<AAIPlayerController>(ParentCharacter->GetController());
AIPC->SetBotConfig(AIPC->BC);
return;
}
//can tick before we actually determine AI state, so just hard force this to always be correct,
//route runner bots do nothing but follow a recorded path
if (BotConfig.BotType == EBotTypes::RouteRunner)
{
AIState.CurrentTask = EAIStates::RouteRunner;
}
//reset current target if no longer valid (ie, dead, switched teams, left server, etc)
if (AIState.CurrentTarget != nullptr && (!IsValid(AIState.CurrentTarget)
|| !FMath::IsNearlyZero(AIState.CurrentTarget->TimeOfDeath) || FMath::IsNearlyZero(AIState.CurrentTarget->GetHealth())))
{
AIState.CurrentTarget = nullptr;
}
//Each tick, we merely follow our current desired behavior, behavior definition is determined in DetermineCurrentTask less frequently.
switch(AIState.CurrentTask)
{
case(EAIStates::ShootAtTarget):
{
ShootAtTarget();
//We want to be moving around a bit randomly in addition to most of our states, to make the bot feel more natural and harder to hit
MoveAround();
break;
}
case(EAIStates::ChangeTarget):
{
ChangeTarget();
MoveAround();
break;
}
case(EAIStates::WaitForBetterShot):
{
WaitForBetterShot();
MoveAround();
break;
}
case(EAIStates::LookingForEnemy):
{
LookForEnemies();
MoveAround();
break;
}
case(EAIStates::MoveToTarget):
{
MoveToTarget();
break;
}
case(EAIStates::RouteRunner):
{
RunRouteSimple();
break;
}
}
}
//Ticks every half second (todo-emallon: make this configurable so we can reduce client load if they are running it locally),
//determining what actions/states the bot actor should be taking. General approach is to give all possible tasks a weighting, increasing in
//likelihood they take that action based on the situation. Weight added to various possible states is influenced by the bots assigned role.
//Highest weighted task option is chosen to be performed.
//todo-emallon try out choosing randomly-ish from all possible tasks, probably with an extra weight added to the 'winner'.
void UMABotAIComponent::DetermineCurrentTask()
{
if (ParentCharacter == nullptr || bIsDead)
{
return;
}
TMap< EAIStates, float> TaskWeights;
EAIStates LastTask = AIState.CurrentTask;
//default to looking around if we have nothing else to do
AIState.CurrentTask = EAIStates::LookingForEnemy;
//we don't want to do the same thing for too long, so we track how long we have been doing our last task to bias against it
float TimeSinceTaskChange = ParentCharacter->GetWorld()->GetTimeSeconds() - TimeOfTaskStart;
AAIPlayerController* AIPC = Cast<AAIPlayerController>(ParentCharacter->GetController());
UMAPracticeComponent* PracticeComponent = AIPC->PracticeComponent;
//if our goal in life is to just run a route, we ignore everything else.
if (BotConfig.BotType == EBotTypes::RouteRunner)
{
AIState.CurrentTask = EAIStates::RouteRunner;
RecentlySeenTargets.Reset();
return;
}
//if we have decided to shoot but haven't yet, continue looking towards our shot. But never for more than a second
if (AIState.bPendingWeaponFire && TimeSinceTaskChange < 1.0f)
{
RecentlySeenTargets.Reset();
AIState.CurrentTask = EAIStates::ShootAtTarget;
return;
}
//Route running bots need to figure out what route they are running prior to us running the determineMoveLoc code
if (BotConfig.BotType == EBotTypes::Offense && AIState.RouteState == EAIRouteState::NoRouteSelected)
{
DetermineRouteToRun();
}
//Figure out where we should move to -- a target player, one of the flags, our route start.
DetermineMoveLocation();
//display a line pointer for each bot to their desired move location
if (bBotDebugMode)
{
ClientDrawDebugLine(
ParentCharacter->GetActorLocation(),
AIState.DesiredMoveLocation,
FColor(0, 255, 0),
2.0f
);
}
//handle our target being dead so we can reset it.
if (AIState.CurrentTarget != nullptr && (!IsValid(AIState.CurrentTarget) || FMath::IsNearlyZero(AIState.CurrentTarget->GetHealth())))
{
AIState.CurrentTarget = nullptr;
}
//We need to ensure we are periodically looking around for new targets, and changing our movement directions.
float TimeSinceLastCheckedForEnemies = ParentCharacter->GetWorld()->GetTimeSeconds() - TimeOfLastLookForEnemy;
float TimeSinceLastMovementChange = ParentCharacter->GetWorld()->GetTimeSeconds() - TimeOfLastMovementTargetChange;
float DistanceToMoveLocation = DistanceBetweenTargets(ParentCharacter->GetActorLocation(), AIState.DesiredMoveLocation);
if (BotConfig.BotType == EBotTypes::Offense)
{
//If we are on O, try to move to our route start or if we are close enough, trigger the route follow to begin.
if (AIState.RouteState == EAIRouteState::MovingToRouteStart)
{
//if we can't quite get to our route start we just teleport there. If they get stuck for a while, increase our teleport distance so they don't do stupid things.
//we can improve this later when we have better movement code. todo-emallon
//3s = 3 * 3 * 10 = 90
//10s = 10 * 10 * 10 = 1000
//20s = 20 * 20 * 10 = 4000
//but cap it so we don't get super weird teleports
if (AIState.MoveTargetType == EAIMoveTargetTypes::RouteStart && DistanceToMoveLocation < TimeSinceLastMovementChange * TimeSinceLastMovementChange * 10 && DistanceToMoveLocation < 5000)
{
StartRouteFollow();
}
else {
TaskWeights.Add(EAIStates::MoveToTarget, 70.0f);
}
}
//while running a route, we only care about changing tasks if we have overshot the flag.
if (AIState.RouteState == EAIRouteState::RunningRoute)
{
//determine where we are, and where the grab happens so we can figure out if we are past it
int priorMarkerNumber = FMath::Clamp(PracticeComponent->CurrentMarkerIndex - 1, 0, PracticeComponent->RouteTrailToRun.MarkerLocations.Num());
int GrabMarker = AIState.CurrentRoute.GrabTime / PracticeComponent->PathRecordMarkerInterval / PracticeComponent->ModulusForLowPrecisionRecordMarkers;
//if we are past our grab time and don't have the flag, we aren't going to be grabbing, so stop our route to clear
//Or, if we are past the end of our route, abandon it.
if ((priorMarkerNumber > GrabMarker && ParentCharacter->CarriedObject == nullptr)
|| priorMarkerNumber == PracticeComponent->RouteTrailToRun.MarkerLocations.Num() - 2)
{
AIState.RouteState = EAIRouteState::AbandonedRoute;
PracticeComponent->EndRoutePathPlayback();
}
else {
TaskWeights.Add(EAIStates::RunningRoute, 170.0f);
}
//todo-emallon add code to abandon route if they are heavily damaged prior to attempting to grab the flag.
//if damaged on route MORE than we expect we should be (due to disc jumps or whatever),
//if (FMath::IsNearlyEqual(ParentCharacter->GetHealth(), PracticeComponent->RouteTrailToRun.MarkerLocations[priorMarkerNumber].Health))
}
if (AIState.RouteState == EAIRouteState::RouteFinished)
{
if (AIState.MoveTargetType == EAIMoveTargetTypes::FriendlyStand && AIState.bIsHoldingFlag) {
if (GameState.FlagState == EAIFlagStates::EnemyFlagTakenFriendlySafe)
{
//if we are trying to cap, that is always most important.
TaskWeights.Add(EAIStates::MoveToTarget, 200.0f);
}
else {
//otherwise stay close to the flag
TaskWeights.Add(EAIStates::MoveToTarget, FMath::Clamp((DistanceToMoveLocation - 500) / 100, 15.0f, 150.0f));
}
}
else {
//If the route is over and we don't have flag, just respawn.
//todo-emallon, once we get a team coordiator to handle bot crosstalk better, they can clear if someone else is coming in.
AIPC->Suicide();
OnDied();
return;
}
}
if (AIState.RouteState == EAIRouteState::AbandonedRoute)
{
//if we have the flag, try to cap if home, or get close if it isn't.
if (AIState.bIsHoldingFlag && (DistanceToMoveLocation > 3000 || GameState.bFriendlyFlagHome))
{
TaskWeights.Add(EAIStates::MoveToTarget, 200.0f);
}
else {
//if we abandoned our route, and don't have the flag, and haven't spawned in a while, suicide and start running routes again.
if (GetWorld()->GetTimeSeconds() - TimeOfLastSpawn > 10 && !AIState.bIsHoldingFlag && GameState.bEnemyFlagHome)
{
AIPC->Suicide();
OnDied();
return;
}
else {
//otherwise default to at least going somewhere.
TaskWeights.Add(EAIStates::MoveToTarget, 20.0f);
}
}
}
}
if (BotConfig.BotType == EBotTypes::Chase)
{
if (AIState.MoveTargetType == EAIMoveTargetTypes::FriendlyFlag && !GameState.bFriendlyFlagHome)
{
if (DistanceToMoveLocation < 10000 || AIState.CurrentTarget == nullptr)
{
//if we are close to a return, or we have no target, we care most about that
TaskWeights.Add(EAIStates::MoveToTarget, 200.0f);
}
else {
//otherwise, if flag isn't home, going towards it is generally quite important.
TaskWeights.Add(EAIStates::MoveToTarget, 70.0f);
}
}
else {
//if we are too far from our stand, and our flag is home, respawn to get closer again.
if (DistanceToMoveLocation > 20000 && GameState.bFriendlyFlagHome == true)
{
AIPC->Suicide();
OnDied();
return;
}
//always care at least a bit about the flag location, unless we are super close to ours already and dont need to return.
if (DistanceToMoveLocation > 500)
{
TaskWeights.Add(EAIStates::MoveToTarget, FMath::Clamp((DistanceToMoveLocation - 500) / 100, 5.0f, 110.0f));
}
}
}
if (BotConfig.BotType == EBotTypes::LO)
{
//as LO, we are a bit more biased towards killing anything we see
if (AIState.MoveTargetType != EAIMoveTargetTypes::EnemyStand || DistanceToMoveLocation > 400)
{
if (AIState.MoveTargetType == EAIMoveTargetTypes::FriendlyFlag && !GameState.bFriendlyFlagHeld && !GameState.bFriendlyFlagHome)
{
TaskWeights.Add(EAIStates::MoveToTarget, FMath::Clamp((DistanceToMoveLocation - 500) / 100, 10.0f, 400.0f));
}
else {
TaskWeights.Add(EAIStates::MoveToTarget, FMath::Clamp((DistanceToMoveLocation - 500) / 100, 30.0f, 40.0f));
}
}
else {
TaskWeights.Add(EAIStates::LookingForEnemy, 10.0f);
}
}
if (BotConfig.BotType == EBotTypes::StayAtHome)
{
//if enemy flag is in field, SaH generally wants to go pick it up, unless it is really far.
if (AIState.MoveTargetType == EAIMoveTargetTypes::EnemyFlag && GameState.bEnemyFlagHeld == false && AIState.bIsHoldingFlag == false)
{
TaskWeights.Add(EAIStates::MoveToTarget, FMath::Clamp((DistanceToMoveLocation - 50) / 100, 65.0f, 150.0f));
}
//if friendly flag is nearby for a return, also very important
else if (AIState.MoveTargetType == EAIMoveTargetTypes::FriendlyFlag && GameState.bFriendlyFlagHome == false && GameState.bFriendlyFlagHeld == false && AIState.bIsHoldingFlag == false)
{
TaskWeights.Add(EAIStates::MoveToTarget, FMath::Clamp((DistanceToMoveLocation - 500) / 100, 20.0f, 100.0f));
}
else {
TaskWeights.Add(EAIStates::MoveToTarget, FMath::Clamp((DistanceToMoveLocation - 500) / 100, 5.0f, 110.0f));
TaskWeights.Add(EAIStates::LookingForEnemy, 6.0f);
}
}
if (RecentlySeenTargets.Num() == 0 && AIState.CurrentTarget == nullptr)
{
//here, we have no good target
//increase our desire to look for dudes by 5 every second
float LookForEnemyTaskWeight = TimeSinceLastCheckedForEnemies * 5.0f;
//if we have already been looking recently, we don't need to KEEP looking. Don't start looking if we haven't been doing something for long
if ((LastTask != EAIStates::LookingForEnemy && TimeSinceTaskChange <= 2.0f) || (LastTask == EAIStates::LookingForEnemy && TimeSinceTaskChange > 2.0f))
{
LookForEnemyTaskWeight = 3.0f;
}
TaskWeights.Add(EAIStates::LookingForEnemy, LookForEnemyTaskWeight);
} else {
//we have at least one target, need to determine how badly we want to shoot at them, or if we should be waiting for a better shot
float TargetHeightAboveGround = 9999999.0f;
if (AIState.CurrentTarget != nullptr)
{
TargetHeightAboveGround = GetHeightAboveGround(AIState.CurrentTarget->GetActorLocation(), false);
}
float WaitForBetterShotWeight = 0.0f;
if (AIState.CurrentTarget != nullptr)
{
// if close to ground AND falling
if (TargetHeightAboveGround < 1000 && AIState.CurrentTarget->GetVelocity().Z < -200.0f)
{
WaitForBetterShotWeight += 9.0f;
}
}
float ChangeTargetWeight = 0.0f;
if (RecentlySeenTargets.Num() > 0)
{
AMACharacter* MostDesirableTarget = AIState.CurrentTarget;
float HighestFocusScore = 0.0f;
//first prune any targets that might have died/left/whatever.
TMap<AMACharacter*, float> ValidRecentlySeenTargets;
for (auto Element : RecentlySeenTargets)
{
float WorldTimeLastSeen = Element.Value; //was working on giving memory to bots again
if (Element.Key != nullptr && Element.Key && IsValid(Element.Key) && Element.Key->IsValidLowLevel() && Element.Key->GetDebugName(Element.Key).Contains("BP_LightCharacter")
&& ParentCharacter->GetWorld()->GetTimeSeconds() - WorldTimeLastSeen < 5.0f)
{
ValidRecentlySeenTargets.Add(Element);
}
}
RecentlySeenTargets = ValidRecentlySeenTargets;
for (auto Element : RecentlySeenTargets)
{
//fetch how desirable this particular target is, so we can find who best to shoot.
float FocusScoreForTarget = GetTargetFocusScore(Element.Key);
if (FocusScoreForTarget > HighestFocusScore)
{
HighestFocusScore = FocusScoreForTarget;
MostDesirableTarget = Element.Key;
}
}
if (MostDesirableTarget == AIState.CurrentTarget)
{
bool bCanSeeTarget = AimAtTarget(false);
if (bCanSeeTarget)
{
TaskWeights.Add(EAIStates::ShootAtTarget, HighestFocusScore);
}
}
else {
TaskWeights.Add(EAIStates::ChangeTarget, HighestFocusScore);
AIState.CurrentTarget = MostDesirableTarget;
}
}
else {
ParentCharacter->SetTrigger(0, false);
}
}
//if we have the flag and the flag is home, nothing else matters over getting there.
if (AIState.bIsHoldingFlag && GameState.bFriendlyFlagHome)
{
TaskWeights.Add(EAIStates::MoveToTarget, 9001.0f);
}
float MaxTaskWeight = 0.0f;
for (auto Element : TaskWeights)
{
if (Element.Value > MaxTaskWeight)
{
MaxTaskWeight = Element.Value;
AIState.CurrentTask = Element.Key;
}
}
//if we are moving to the stand but can't actually DO anything there, switch to look for targets/wander so we prevent the spinning in place issues
//if at the enemy stand and the flag isn't home, look for things to shoot.
//if at the friendly flag and we aren't holding the flag and the flag isn't home (aka we are capping), look for enemies to shoot.
if(AIState.CurrentTask == EAIStates::MoveToTarget && DistanceToMoveLocation < 300
&& ((AIState.MoveTargetType == EAIMoveTargetTypes::EnemyStand && GameState.bEnemyFlagHome == false)
|| (AIState.MoveTargetType == EAIMoveTargetTypes::FriendlyStand && (AIState.bIsHoldingFlag == false || GameState.bFriendlyFlagHome == false))))
{
AIState.CurrentTask = EAIStates::LookingForEnemy;
}
FString AISTateString = "Undefined";
switch (AIState.CurrentTask)
{
case(EAIStates::ChangeTarget):
AISTateString = "Change Target";
break;
case(EAIStates::LookingForEnemy):
AISTateString = "Looking for Enemy";
break;
case(EAIStates::MoveToTarget):
AISTateString = "Move To Target";
break;
case(EAIStates::RouteRunner):
AISTateString = "Route RUnner";
break;
case(EAIStates::RunningRoute):
AISTateString = "Running ROute";
break;
case(EAIStates::ShootAtTarget):
AISTateString = "Shoot at target";
break;
case(EAIStates::WaitForBetterShot):
AISTateString = "Wait for better shot";
break;
}
AISTateString = "Task: " + AISTateString;
//GEngine->AddOnScreenDebugMessage(73, 130.1f, FColor::Black, AISTateString);
//GEngine->AddOnScreenDebugMessage(75, 130.1f, FColor::Red, FString::Printf(TEXT("task time: %f"), TimeSinceTaskChange));
if (AIState.CurrentTask != LastTask)
{
TimeOfTaskStart = ParentCharacter->GetWorld()->GetTimeSeconds();
AIState.IsTaskInitialized = false;
}
//todo-emallon hack that removes the bots memory. Right now we aren't properly pruning recently seen targets when characters die
//so we crash when checking focus scores for the already dead targets sometimes.
//need to probably change this to a map of TWeakObjectPtr instead.
RecentlySeenTargets.Reset();
}
void UMABotAIComponent::DetermineRouteToRun()
{
//if we haven't added any routes to our capper, we can't choose a route, now can we?
if (BotConfig.RouteTrailNames.Num() == 0)
{
return;
}
if (AAIPlayerController* AIPC = Cast<AAIPlayerController>(ParentCharacter->GetController()))
{
int BotRouteToRun = FMath::RandRange(0, BotConfig.RouteTrailNames.Num() - 1);
FString BotRoute = BotConfig.RouteTrailNames[BotRouteToRun];
UMAPracticeComponent* PracticeComponent = AIPC->PracticeComponent;
int TeamID = 0;
if (AMAPlayerState* PS = Cast<AMAPlayerState>(ParentCharacter->GetController()->PlayerState))
{
TeamID = PS->GetTeamId();
}
AIState.CurrentRoute = PracticeComponent->GetRouteTrailByName(BotRoute, TeamID); //todo-emallon use a RouteTrailLite here so we don't pass all marker locations/input around
if (AIState.CurrentRoute.MarkerLocations.Num() > 0)
{
AIState.RouteStartLocation = AIState.CurrentRoute.MarkerLocations[0].Location;
}
AIState.RouteState = EAIRouteState::MovingToRouteStart;
}
}
void UMABotAIComponent::DetermineMoveLocation()
{
if (ParentCharacter == nullptr)
{
return;
}
float TargetDistance = DistanceToTarget(AIState.CurrentTarget);
FVector OriginalMoveLocation = AIState.DesiredMoveLocation;
EAIMoveTargetTypes OriginalMoveLocationType = AIState.MoveTargetType;
AIState.DesiredMoveLocation = FVector::ZeroVector;
//if we need to start a route, then we just go ASAP to route start.
if (BotConfig.BotType == EBotTypes::Offense && AIState.RouteState == EAIRouteState::MovingToRouteStart)
{
AIState.MoveTargetType = EAIMoveTargetTypes::RouteStart;
AIState.DesiredMoveLocation = AIState.RouteStartLocation;
return;
}
//first, get the latest game state.
for (TActorIterator<AMACTFFlag> ActorItr(GetWorld()); ActorItr; ++ActorItr)
{
AMACTFFlag *Flag = *ActorItr;
uint8 BotTeamId = ParentCharacter->GetTeamId();
uint8 FlagTeamId = Flag->GetTeamId();
bool bEnemyFlag = BotTeamId != FlagTeamId;
if (bEnemyFlag)
{
GameState.EnemyFlagLocation = Flag->GetActorLocation();
GameState.bEnemyFlagHome = Flag->IsHome();
GameState.bEnemyFlagHeld = Flag->StateName == CarriedObjectState::Held;
AIState.DistanceToEnemyFlag = DistanceBetweenTargets(ParentCharacter->GetActorLocation(), Flag->GetActorLocation());
}
else {
GameState.FriendlyFlagLocation = Flag->GetActorLocation();
GameState.bFriendlyFlagHome = Flag->IsHome();
GameState.bFriendlyFlagHeld = Flag->StateName == CarriedObjectState::Held;
AIState.DistanceToFriendlyFlag = DistanceBetweenTargets(ParentCharacter->GetActorLocation(), Flag->GetActorLocation());
}
}
if (GameState.bEnemyFlagHome && GameState.bFriendlyFlagHome)
{
GameState.FlagState = EAIFlagStates::BothFlagsHome;
}else if (!GameState.bEnemyFlagHome && GameState.bFriendlyFlagHome)
{
GameState.FlagState = EAIFlagStates::EnemyFlagTakenFriendlySafe;
}else if (GameState.bEnemyFlagHome && !GameState.bFriendlyFlagHome)
{
GameState.FlagState = EAIFlagStates::FriendlyTakenEnemyHome;
}else if (!GameState.bEnemyFlagHome && !GameState.bFriendlyFlagHome)
{
GameState.FlagState = EAIFlagStates::Standoff;
}
AIState.bIsHoldingFlag = ParentCharacter->CarriedObject != nullptr;
//If we have the flag we always try to cap.
if (AIState.bIsHoldingFlag)
{
AIState.MoveTargetType = EAIMoveTargetTypes::FriendlyStand;
AIState.DesiredMoveLocation = GameState.FriendlyStandLocation;
}
//If chase, we always care about our flag unless we are holding.
if (!AIState.bIsHoldingFlag && BotConfig.BotType == EBotTypes::Chase)
{
AIState.MoveTargetType = EAIMoveTargetTypes::FriendlyFlag;
AIState.DesiredMoveLocation = GameState.FriendlyFlagLocation;
}
//if we are on O, we care about returns in standoffs and otherwise the enemy flag.
if (!AIState.bIsHoldingFlag && (BotConfig.BotType == EBotTypes::Offense || BotConfig.BotType == EBotTypes::LO))
{
//if enemy flag is dropped and close, we go for that
if (GameState.bEnemyFlagHome == false && GameState.bEnemyFlagHeld == false && AIState.DistanceToEnemyFlag < 5000)
{
AIState.MoveTargetType = EAIMoveTargetTypes::EnemyFlag;
AIState.DesiredMoveLocation = GameState.EnemyFlagLocation;
}
//if friendly flag is dropped and close, we prioritize that next
else if (GameState.bFriendlyFlagHeld == false && GameState.bFriendlyFlagHome == false && AIState.DistanceToFriendlyFlag < 5000)
{
AIState.MoveTargetType = EAIMoveTargetTypes::FriendlyFlag;
AIState.DesiredMoveLocation = GameState.FriendlyFlagLocation;
}else if (GameState.FlagState == EAIFlagStates::Standoff)
{
AIState.MoveTargetType = EAIMoveTargetTypes::FriendlyFlag;
AIState.DesiredMoveLocation = GameState.FriendlyFlagLocation;
} else {
if (BotConfig.BotType == EBotTypes::Offense)
{
AIState.MoveTargetType = EAIMoveTargetTypes::EnemyFlag;
AIState.DesiredMoveLocation = GameState.EnemyFlagLocation;
}
else if (BotConfig.BotType == EBotTypes::LO)
{
if (GameState.FlagState == EAIFlagStates::EnemyFlagTakenFriendlySafe)
{
AIState.MoveTargetType = EAIMoveTargetTypes::EnemyFlag;
AIState.DesiredMoveLocation = GameState.EnemyFlagLocation;
}
else {
AIState.MoveTargetType = EAIMoveTargetTypes::EnemyStand;
AIState.DesiredMoveLocation = GameState.EnemyStandLocation;
}
}
}
}
//Stay at home cares about friendly flag before standoffs, and enemy during standoffs.
if (BotConfig.BotType == EBotTypes::StayAtHome)
{
//in general, SaH goes to their own stand
AIState.MoveTargetType = EAIMoveTargetTypes::FriendlyStand;
AIState.DesiredMoveLocation = GameState.FriendlyStandLocation;
//if you are in a standoff and the flag is close to you, try to pick it up
if (GameState.FlagState == EAIFlagStates::Standoff
|| (GameState.FlagState == EAIFlagStates::EnemyFlagTakenFriendlySafe && AIState.DistanceToEnemyFlag < 10000 && GameState.bEnemyFlagHeld == false))
{
AIState.MoveTargetType = EAIMoveTargetTypes::EnemyFlag;
AIState.DesiredMoveLocation = GameState.EnemyFlagLocation;
}
else {
//if friendly flag has been taken, and is close and we don't have their flag, chase.
if (GameState.FlagState == EAIFlagStates::FriendlyTakenEnemyHome && AIState.DistanceToFriendlyFlag < 10000)
{
AIState.MoveTargetType = EAIMoveTargetTypes::FriendlyFlag;
AIState.DesiredMoveLocation = GameState.FriendlyFlagLocation;
}
}
}
float DistanceToMoveLocation = DistanceBetweenTargets(ParentCharacter->GetActorLocation(), AIState.DesiredMoveLocation);
//if we are relatively close to where we want to be and have a target, go for our target.
if (AIState.CurrentTarget != nullptr && TargetDistance < 20000 && DistanceToMoveLocation < 10000)
{
AIState.MoveTargetType = EAIMoveTargetTypes::EnemyTarget;
AIState.DesiredMoveLocation = AIState.CurrentTarget->GetActorLocation();
}
//distance to flag where it being on the ground overrides everything else, differs per position
float FriendlyFlagOverrideDistance = 5000.0f;
float EnemyFlagOverrideDistance = 5000.0f;
if (BotConfig.BotType == EBotTypes::StayAtHome)
{
EnemyFlagOverrideDistance = 15000;
FriendlyFlagOverrideDistance = 10000;
}
if (BotConfig.BotType == EBotTypes::Chase)
{
FriendlyFlagOverrideDistance = 15000;
}
//if the flag is in the field, we can care about that most, usually.
if (AIState.DistanceToFriendlyFlag < FriendlyFlagOverrideDistance && !GameState.bFriendlyFlagHeld
&& (GameState.FlagState == EAIFlagStates::FriendlyTakenEnemyHome || GameState.FlagState == EAIFlagStates::Standoff))
{
AIState.MoveTargetType = EAIMoveTargetTypes::FriendlyFlag;
AIState.DesiredMoveLocation = GameState.FriendlyFlagLocation;
}
if (AIState.DistanceToEnemyFlag < EnemyFlagOverrideDistance && !GameState.bEnemyFlagHeld
&& (GameState.FlagState == EAIFlagStates::EnemyFlagTakenFriendlySafe || GameState.FlagState == EAIFlagStates::Standoff))
{
AIState.MoveTargetType = EAIMoveTargetTypes::EnemyFlag;
AIState.DesiredMoveLocation = GameState.EnemyFlagLocation;
}
//If we have the flag and can cap, we always try to cap.
if (AIState.bIsHoldingFlag && GameState.bFriendlyFlagHome)
{
AIState.MoveTargetType = EAIMoveTargetTypes::FriendlyStand;
AIState.DesiredMoveLocation = GameState.FriendlyStandLocation;
}
//not fully accurate yet, doesnt track changing enemy targets.
if (OriginalMoveLocationType != AIState.MoveTargetType)
{
TimeOfLastMovementTargetChange = GetWorld()->GetTimeSeconds();
//start of prototype multi-waypoint moves to allow for planning of more complex movements around geometry. barely started.
/* FVector StartLocation = ParentCharacter->GetActorLocation();
FVector EndLocation = AIState.DesiredMoveLocation; // Raytrace end point.
FCollisionQueryParams CollisionParams = FCollisionObjectQueryParams::AllStaticObjects;
CollisionParams.AddIgnoredActor(ParentCharacter);
// Raytrace for overlapping actors.
FHitResult HitResult;
if (GetWorld())
{
GetWorld()->LineTraceSingleByObjectType(
OUT HitResult,
StartLocation,
EndLocation,
FCollisionObjectQueryParams(ECollisionChannel::ECC_WorldStatic),
CollisionParams
);
FColor LineColor;
if (HitResult.GetActor()) LineColor = FColor::Red;
else LineColor = FColor::Green;
DrawDebugLine(
ParentCharacter->GetWorld(),
StartLocation,
EndLocation,
LineColor,
true,
10.f,
ESceneDepthPriorityGroup::SDPG_World,
10.f
);
//we hit something in between us and flag, try going up first.
if (HitResult.GetActor())
{
FVector EndLocationWaypoint = AIState.DesiredMoveLocation;
EndLocationWaypoint.Z += 600.0f; //200 =~ height of flag
GetWorld()->LineTraceSingleByObjectType(
OUT HitResult,
StartLocation,
EndLocationWaypoint,
FCollisionObjectQueryParams(ECollisionChannel::ECC_WorldStatic),
CollisionParams
);
if (HitResult.GetActor()) LineColor = FColor::Red;
else LineColor = FColor::Green;
DrawDebugLine(
ParentCharacter->GetWorld(),
StartLocation,
EndLocationWaypoint,
LineColor,
true,
10.f,
ESceneDepthPriorityGroup::SDPG_World,
10.f
);
GetWorld()->LineTraceSingleByObjectType(
OUT HitResult,
EndLocationWaypoint,
EndLocation,
FCollisionObjectQueryParams(ECollisionChannel::ECC_WorldStatic),
CollisionParams
);
if (HitResult.GetActor()) LineColor = FColor::Red;
else LineColor = FColor::Green;
DrawDebugLine(
ParentCharacter->GetWorld(),
EndLocationWaypoint,
EndLocation,
LineColor,
true,
10.f,
ESceneDepthPriorityGroup::SDPG_World,
10.f
);
}
} */
}
}
void UMABotAIComponent::ShootAtTarget()
{
SelectBestWeapon();
AimAtTarget(true);
}
void UMABotAIComponent::WaitForBetterShot()
{
AimAtTarget(false);
SelectBestWeapon();
ParentCharacter->SetTrigger(0, false);
}
void UMABotAIComponent::ChangeTarget()
{
AimAtTarget(false);
ParentCharacter->SetTrigger(0, false);
}
void UMABotAIComponent::MoveToTarget()
{
if (ParentCharacter == nullptr || ParentCharacter->GetController() == nullptr)
{
return;
}
float HeightAboveGround = GetHeightAboveGround(ParentCharacter->GetActorLocation(), false);
float DistanceToDesiredLocation = DistanceBetweenTargets(ParentCharacter->GetActorLocation(), AIState.DesiredMoveLocation);
//first, if we are far from our desired location (enemy player or our flag) we move towards them.
FVector VectorToTarget = AIState.DesiredMoveLocation - ParentCharacter->GetActorLocation();
FRotator RotatorToLookAtMoveLocation = UKismetMathLibrary::MakeRotFromXZ(VectorToTarget.GetSafeNormal(), ParentCharacter->GetActorUpVector());
//if we just shot at something, we want to look at what we shot at, not at our move target, and then look back over time.
//otherwise we get really jerky orientations from the bots.
float TimeSinceLastShot = ParentCharacter->GetWorld()->GetTimeSeconds() - TimeOfLastShot;
//0s since last shot = look at shot, full skew 3-0=3/3=1
//3s or greater - 0 skew 3-3=0/3=0, 3-1.5=1.5/3=.5
float SkewFactor = (3.0f - FMath::Min(TimeSinceLastShot, 3.0f)) / 3.0f;
RotatorToLookAtMoveLocation.Pitch += RandomPitchSkew * SkewFactor;
RotatorToLookAtMoveLocation.Yaw += RandomYawSkew * SkewFactor;
ParentCharacter->GetController()->SetControlRotation(RotatorToLookAtMoveLocation);
FRotator ActorRot = RotatorToLookAtMoveLocation;
ActorRot.Roll = 0.0f;
ActorRot.Pitch = 0.0f;
ParentCharacter->SetActorRotation(ActorRot);
ParentCharacter->MoveForward(1.0f);
//we don't want to skii if we are sliding backwards from our target, since we won't gain mommentum going the correct direction
float DistanceToTargetPlusVelocity = DistanceToDesiredLocation + DistanceBetweenTargets(ParentCharacter->GetActorLocation() + ParentCharacter->GetVelocity(), AIState.DesiredMoveLocation);
if (HeightAboveGround < 100 && DistanceToDesiredLocation > 1000 && DistanceToTargetPlusVelocity > DistanceToDesiredLocation)
{
ParentCharacter->Skate();
}
else {
ParentCharacter->StopSkating();
}
float HeightAboveTargetLoc = HeightAbove(AIState.DesiredMoveLocation);
//TODO improve amount of jets needed to go X height formula
//1000 below, -1000. Z velocity goes to like 3-4k when skiing up fast. If we are close, and already have velocity, we stop jetting.
bool bWasPreviouslyJetting = bIsJetting;
float TimeOfSinceJetChange = ParentCharacter->GetWorld()->GetTimeSeconds() - TimeOfLastJetChange;
float CharEnergy = ParentCharacter->GetEnergy();
bool HeightAboveTargetCheck = HeightAboveTargetLoc < 0;
//we want to give jet energy some time to recharge if it is low, before trying to jet
bool EnergyRechargeCheck = (bWasPreviouslyJetting || TimeOfSinceJetChange > 2.0f || CharEnergy > 100);
float VelocityZ = ParentCharacter->GetVelocity().Z;
//controls how far above a target we overshoot so we don't accidentally not get all the way up.
float OvershootFudgeFactor = 300.0f;
//stop jetting early so we don't go WAY above it
bool OvershootCheck = !(VelocityZ / 2 + HeightAboveTargetLoc > OvershootFudgeFactor && TimeOfSinceJetChange > 1.0f);
//bots are bad with energy for now, so blatently cheat //todo-emallon REMOVE ME
if (CharEnergy < 50.5f)
{
ParentCharacter->GetVitals()->SetEnergy(100.0f);
}
if (HeightAboveTargetCheck && EnergyRechargeCheck && OvershootCheck && CharEnergy > 0.01f)
{
bIsJetting = true;
ParentCharacter->Jump();
ParentCharacter->Jet();
}
else {
bIsJetting = false;
ParentCharacter->StopJumping();
ParentCharacter->StopJetting();
}
if (bWasPreviouslyJetting != bIsJetting)
{
TimeOfLastJetChange = ParentCharacter->GetWorld()->GetTimeSeconds();
}
}
//most of the time when bots are doing something (looking for enemies, shooting at someone, defending the flag, etc) we want them to be doing some minor movements
//to make them look more natural.
void UMABotAIComponent::MoveAround()
{
if (ParentCharacter == nullptr || ParentCharacter->GetController() == nullptr || BotConfig.BotType == EBotTypes::StationaryDefense)
{
return;
}
float HeightAboveGround = GetHeightAboveGround(ParentCharacter->GetActorLocation(), false);
float DistanceToDesiredLocation = DistanceBetweenTargets(ParentCharacter->GetActorLocation(), AIState.DesiredMoveLocation);
//if we are already close to the target location, we move around randomly.
float TimeSinceLastMovementChange = ParentCharacter->GetWorld()->GetTimeSeconds() - TimeOfLastMovementChange;
if (TimeSinceLastMovementChange > 1.0f)
{
if (FMath::RandRange(0.0f, 3.0f) + TimeSinceLastMovementChange > 3.0f)
{
//If we are where we want to be, and no enemy is close, we want to just chill and not move too randomly most of the time.
if (AIState.CurrentTask == EAIStates::LookingForEnemy || ((AIState.CurrentTask == EAIStates::ShootAtTarget && DistanceToTarget(AIState.CurrentTarget) > 5000)
&& FMath::RandRange(0, 3) > 1))
{
ActiveMovementType = EPlayerRecordableInputTypes::StopSkii;
}
else {
int RandomMovementType = FMath::RandRange(0, 3);
switch (RandomMovementType)
{
case 0:
ActiveMovementType = EPlayerRecordableInputTypes::Forward;
break;
case 1:
ActiveMovementType = EPlayerRecordableInputTypes::Backwards;
break;
case 2:
ActiveMovementType = EPlayerRecordableInputTypes::Left;
break;
case 3:
ActiveMovementType = EPlayerRecordableInputTypes::Right;
break;
}
}
TimeOfLastMovementChange = ParentCharacter->GetWorld()->GetTimeSeconds();
}
}
float TimeSinceLastJetChange = ParentCharacter->GetWorld()->GetTimeSeconds() - TimeOfLastJetChange;
if (TimeSinceLastJetChange > 1.0f && (ParentCharacter->GetEnergy() > 40 || ParentCharacter->GetEnergy() < 5))
{
if (FMath::RandRange(0.0f, 3.0f) + TimeSinceLastJetChange > 3.0f)
{
bIsJetting = !bIsJetting;
TimeOfLastJetChange = ParentCharacter->GetWorld()->GetTimeSeconds();
}
}
//now that we figured out what we SHOULD do, we can implement it.
//first, stop skiing, we are already close
ParentCharacter->StopSkating();
//then set jet status
if (bIsJetting)
{
ParentCharacter->Jump();
ParentCharacter->Jet();
}
else {
ParentCharacter->StopJumping();
ParentCharacter->StopJetting();
}
//and finally set where we are moving to.
switch (ActiveMovementType)
{
case(EPlayerRecordableInputTypes::Forward):
ParentCharacter->MoveForward(1.0f);
break;
case(EPlayerRecordableInputTypes::Backwards):
ParentCharacter->MoveForward(-1.0f);
break;
case(EPlayerRecordableInputTypes::Left):
ParentCharacter->MoveRight(-1.0f);
break;
case(EPlayerRecordableInputTypes::Right):
ParentCharacter->MoveRight(1.0f);
break;
}
}
//standard bot route running
void UMABotAIComponent::StartRouteFollow()
{
if (AIState.IsTaskInitialized || AIState.CurrentRoute.MarkerLocations.Num() < 1)
{
return;
}
if (AAIPlayerController* AIPC = Cast<AAIPlayerController>(ParentCharacter->GetController()))
{
UMAPracticeComponent* PracticeComponent = AIPC->PracticeComponent;
//set up options for how we want to run the route (these mostly matter for practice mode, and will always be like this for a real bot running AI)
PracticeComponent->SelectedRouteTrail = AIState.CurrentRoute;
PracticeComponent->RouteTrailMarkerIndex = 0;