ASightAIController::ASightAIController() {
//Creating the AI Perception Component
PerceptionComponent =
CreateDefaultSubobject<UAIPerceptionComponent>(TEXT("SightPerceptionComponent"));
SightConfig = CreateDefaultSubobject<UAISenseConfig_Sight>(FName("SightConfig"));
//Configuring the Sight Sense
SightConfig->SightRadius = 600;
SightConfig->LoseSightRadius = 700;
SightConfig->DetectionByAffiliation.bDetectEnemies = true;
SightConfig->DetectionByAffiliation.bDetectNeutrals = true;
SightConfig->DetectionByAffiliation.bDetectFriendlies = true;
//Assigning the Sight Sense to the AI Perception Component
PerceptionComponent->ConfigureSense(*SightConfig);
PerceptionComponent->SetDominantSense(SightConfig->GetSenseImplementation()
);
//Binding the OnTargetPerceptionUpdate function
PerceptionComponent->OnTargetPerceptionUpdated.AddDynamic(this, &ASightAIController::OnTargetPerceptionUpdate);
}
void ASightAIController::OnTargetPerceptionUpdate(AActor* Actor,
FAIStimulus Stimulus)
{
//Retrieving Perceived Actors
TArray<AActor*> PerceivedActors;
PerceptionComponent->GetPerceivedActors(TSubclassOf<UAISense_Sight>(), PerceivedActors);
//Calculating the Number of Perceived Actors and if the current target Left or Entered the field of view.
bool isEntered = PerceivedActors.Contains(Actor);
int NumberObjectSeen = PerceivedActors.Num();
}
最后,我们需要将这些信息打包成一个格式化的字符串,然后打印在屏幕上:
void ASightAIController::OnTargetPerceptionUpdate(AActor* Actor, FAIStimulus Stimulus)
{
//Retrieving Perceived Actors
TArray<AActor*> PerceivedActors;
PerceptionComponent->GetPerceivedActors(TSubclassOf<UAISense_Sight>(), PerceivedActors);
//Calculating the Number of Perceived Actors and if the current target Left or Entered the field of view.
bool isEntered = PerceivedActors.Contains(Actor);
int NumberObjectSeen = PerceivedActors.Num();
//Formatting the string and printing it
FString text = FString(Actor->GetName() + " has just " + (isEntered ? "Entered" : "Left") + " the field of view. Now " + FString::FromInt(NumberObjectSeen) + " objects are visible.");
if (GEngine) {
GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Turquoise, text);
}
UE_LOG(LogTemp, Warning, TEXT("%s"), *text);
}