UEC++学习(十二)AI感知组件AIPerceptionComponent

本文介绍了如何在UnrealEngine中创建一个名为AIPerceptionComponent的类,用于AI角色在视野内检测并追踪最近的敌人。通过GetClosestEnemy函数获取视野范围内的角色,并在Tick函数中调整AI的聚焦方向。
摘要由CSDN通过智能技术生成

目录

 创建组件

在视野内看向玩家


 创建组件

创建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通过感知组件朝向角色

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值