跳到主内容
Documentation

3.注册 AActor AI视觉感知刺激源.md

2025/12/16预计阅读 2 分钟

实现目标

当怪物行走过程中,我的怪物能够感知到放在路边的陷阱(AActor)。

因为 pawn类型是自动感知的,所以只需要在陷阱上添加一个感知刺激源组件。

在陷阱AActor中添加

MyBaseTrap.h


	//AI视觉感知刺激源
	UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Trap", DisplayName="感知组件")
	UAIPerceptionStimuliSourceComponent* PerceptionStimuliSourceComponent;

MyBaseTrap.cpp

初始化



AMyTrapBase::AMyTrapBase()
{
	
	// AI感知刺激源初始化
	PerceptionStimuliSourceComponent = CreateDefaultSubobject<UAIPerceptionStimuliSourceComponent>(
		TEXT("PerceptionStimuliSourceComponent"));
	PerceptionStimuliSourceComponent->bAutoRegister = true; //自动注册
	
}

注册的函数不要在构造函数里面调用,否则会失效,因为里面的函数调用了GetWorld()函数。

PostInitializeComponents中调用注册函数,在BeginPlay中调用注册函数也可以。


void AMyTrapBase::PostInitializeComponents()
{
	Super::PostInitializeComponents();
	PerceptionStimuliSourceComponent->RegisterForSense(UAISense_Sight::StaticClass());//可被怪物看到
	PerceptionStimuliSourceComponent->RegisterWithPerceptionSystem(); //注册到感知系统
}

这样就可以了,AI怪物就能视觉感知到陷阱了。

返回顶部