目录
创建组件
创建AIPerceptionComponent类,命名为STUAIPerceptionComponent
在AIController.h中创建感知组件变量
class USTUAIPerceptionComponent; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Component") USTUAIPerceptionComponent* STUAIPerceptionComponent;
在构造函数中对其初始化,
SetPerceptionComponet:自带函数,对组件赋值
ASTUAIController::ASTUAIController() { STUAIPerceptionComponent = CreateDefaultSubobject<USTUAIPerceptionComponent>("STUAIPerceptionComponent"); SetPerceptionComponent(*STUAIPerceptionComponent); }
在蓝图中 AI Sight Config用于视野感知
在视野内看向玩家
在AIPerceptionComponent.h中创建一个函数用于返回看到的角色
AActor* GetClosestEnemy() const;
在CPP中
GetCurrentlyPerceivedActors(UAISense_Sight::StaticClass(), PercieveActors):返回视野内的所有actor,参数:蓝图中设置的DominantSense值,用于存储返回actor的数组
MAX_FLT:UE自带宏,返回一个最大的数
#include "AIController.h" #include "STUUtil.h" #include "Components/STUHealthComponent.h" #include "Perception/AISense_Sight.h" AActor* USTUAIPerceptionComponent::GetClosestEnemy() const { TArray<AActor*> PercieveActors; //返回Ai视野范围内检测到的所有actor GetCurrentlyPerceivedActors(UAISense_Sight::StaticClass(), PercieveActors); if (PercieveActors.Num() == 0) { return nullptr; } AAIController* Controller = Cast<AAIController>(GetOwner()); if (!Controller) { return nullptr; } APawn* Pawn = Controller->GetPawn(); if (!Pawn) { return nullptr; } //MAX_FLT:ue自带宏 float BestDistance = MAX_FLT; AActor* BestPawn = nullptr; for (AActor * PercieveActor : PercieveActors) { //此处是判断角色是否死亡,可以换成你们自己的逻辑 USTUHealthComponent* HealthComponent = STUUtil::GetSTUPlayerComponent<USTUHealthComponent>(PercieveActor); if (HealthComponent && !HealthComponent->IsDead()) { //计算actor和ai之间的距离 float CurrentDistance = (PercieveActor->GetActorLocation() - Pawn->GetActorLocation()).Size(); if (CurrentDistance < BestDistance) { //返回离Ai最近的actor BestDistance = CurrentDistance; BestPawn = PercieveActor; } } } return BestPawn; }
然后再AIController的Tick函数中调用,这里也可以在别的地方,随意
SetFocus():设置需要朝向的Actor
void ASTUAIController::Tick(float DeltaTime) { Super::Tick(DeltaTime); AActor* AimActor = STUAIPerceptionComponent->GetClosestEnemy(); SetFocus(AimActor); }
最终效果:
使用 ” 键查看ai调试信息,按下 4 可以查看perception的信息
AI通过感知组件朝向角色