setup AI Perception and forgatting behavior from Blackboard

This commit is contained in:
Caleb Buhungiro
2025-09-14 23:22:37 +08:00
parent 1c1c56ea46
commit f84a711b4f
4 changed files with 30 additions and 9 deletions

View File

@@ -102,3 +102,6 @@ CategorySlot7=Seven
CategorySlot8=Eight
CategorySlot9=Nine
[/Script/AIModule.AISystem]
bForgetStaleActors=True

Binary file not shown.

View File

@@ -26,6 +26,7 @@ ACAIController::ACAIController()
AIPerceptionComponent->ConfigureSense(*SightConfig);
AIPerceptionComponent->OnTargetPerceptionUpdated.AddDynamic(this, &ThisClass::TargetPerceptionUpdated);
AIPerceptionComponent->OnTargetPerceptionForgotten.AddDynamic(this, &ACAIController::TargetForgotten);
}
void ACAIController::OnPossess(APawn* InPawn)
@@ -52,18 +53,22 @@ void ACAIController::Tick(float DeltaTime)
void ACAIController::TargetPerceptionUpdated(AActor* TargetActor, FAIStimulus Stimulus)
{
UE_LOG(LogTemp, Warning, TEXT("Saw you"))
// GEngine->AddOnScreenDebugMessage(
// -1, 12.f, FColor::Blue,
// FString::Printf(TEXT("saw you")));
if (Stimulus.WasSuccessfullySensed())
{
if (!GetCurrentTarget()) SetCurrentTarget(TargetActor);
}
else
{
if (GetCurrentTarget() == TargetActor) SetCurrentTarget(nullptr);
}
}
void ACAIController::TargetForgotten(AActor* ForgottenActor)
{
if (!ForgottenActor) return;
if (GetCurrentTarget() == ForgottenActor)
{
SetCurrentTarget(GetNextPerceivedActor());
}
}
@@ -71,8 +76,7 @@ const UObject* ACAIController::GetCurrentTarget() const
{
if (const auto BlackboardComponent{GetBlackboardComponent()})
{
const auto Target{BlackboardComponent->GetValueAsObject(BlackboardTargetName)};
return Target;
return BlackboardComponent->GetValueAsObject(BlackboardTargetName);
}
return nullptr;
}
@@ -85,3 +89,14 @@ void ACAIController::SetCurrentTarget(AActor* NewTarget)
if (NewTarget) BlackboardComponent->SetValueAsObject(BlackboardTargetName, NewTarget);
else BlackboardComponent->ClearValue(BlackboardTargetName);
}
AActor* ACAIController::GetNextPerceivedActor() const
{
if (PerceptionComponent)
{
TArray<AActor*> Actors;
AIPerceptionComponent->GetPerceivedHostileActors(Actors);
if (Actors.Num() != 0) return Actors[0];
}
return nullptr;
}

View File

@@ -28,6 +28,8 @@ private:
FName BlackboardTargetName {"Target"};
UFUNCTION()
void TargetPerceptionUpdated(AActor* TargetActor, FAIStimulus Stimulus);
UFUNCTION()
void TargetForgotten(AActor* ForgottenActor);
UPROPERTY(EditDefaultsOnly, Category="AI Behavior")
UBehaviorTree* BehaviorTree;
@@ -40,4 +42,5 @@ private:
UFUNCTION()
const UObject* GetCurrentTarget() const ;
void SetCurrentTarget(AActor* NewTarget);
AActor * GetNextPerceivedActor() const;
};