目录
前言
在上一篇(UE5.1】NPC人工智能------04 NPC巡逻)中我们已经实现了NPC狮子巡逻功能,本篇我们要介绍的功能是给狮子添加视觉,让其看到玩家时就跑过来。
效果

步骤
一、添加视觉感知与感知刺激源
- 由于几乎所有NPC都需要视觉感知,因此我们直接在所有AI控制器的父类"BP_NPC_AIController"中添加一个AI感知组件

在感官配置中添加一个元素,该元素设置为"AI视力配置"

这里设置视线半径为1000,失去实现半径为1200,归属检测都开启,主导感官为"AISence_Sight"

- 为了让NPC狮子能感知到玩家角色,我们还需打开角色蓝图,然后添加一个AI感知刺激源组件

勾选"自动注册为源",添加一个注册为感官的源,选择"AISence_Sight"

二、AI调试
AI调试说明见官方文档:https://dev.epicgames.com/documentation/zh-cn/unreal-engine/ai-debugging-in-unreal-engine
这里简要阐述一下,首先按引号键启用AI调试

通过按小键盘的数字键0、1、2、3、4键分别开启或关闭调试信息


当NPC狮子看到视觉刺激源后,会在场景中生成一个绿色的球,表示感知到的位置

绿色圆形表示NPC狮子的可视边界,粉色表示失去视线的边界

三、NPC感知到玩家就跑向玩家
- 回到AI控制器"BP_NPC_AIController"中,选中AI感知组件,然后添加一个"目标感知更新时"事件。

在事件图表中添加如下节点,首先判断是否成功感知,再判断感知到的actor是否为玩家角色

- 回到黑板"Blackboard_Lion"中,新建一个object类型变量

这里命名为"Target Character",表示NPC狮子看到的目标角色

该变量的键类型中的基类设置为玩家角色"BP_ThirdPersonCharacter"

- 回到AI控制器"BP_NPC_AIController"的事件图表中,添加如下节点。当成功感知时,将黑板中的变量"Target Character"设置为"BP_ThirdPersonCharacter",当失去感知时,将"Target Character"置空。

变量"Key_TargetCharacter"的变量类型为命名,默认值为"Target Character"

- 打开行为树"BT_Lion",添加一个"Selector(选择器合成节点)"

鼠标右键点击"Sequence"节点的上部,选择"添加装饰器-》Blackground"

选中装饰器,然后在细节面板中设置黑板键为"TargetCharacter"

此时只要黑板中的变量"TargetCharacter"没有被设置的时候,就会执行"Sequence"及其后续的内容,然后给"Selector"节点返回一个true。

如果黑板中的变量"TargetCharacter"被设置了(表示狮子NPC感知到了玩家),就让狮子移动到"TargetCharacter"

此时运行可以看到NPC狮子一开始在巡逻,当感知到玩家后就会跑向玩家

但是有一点问题,就是当NPC狮子跟上玩家后会穿过玩家,我们可以在行为树中选中"MoveTo"节点,然后增加"可接受半径"

如果想增加NPC狮子的感知半径,可以在AI控制器中调整

如果想提高狮子的转向速度,可以在"Character_Lion"的类默认值中提高旋转速率。

四、优化NPC反应
当前还存在的问题是,当狮子看见玩家后会经过一定的延迟后才跑向玩家。这是因为在行为树中"Sequence"节点会从左到右全部执行后才返回到"Selector",由于有"Wait"的存在,因此在"Sequence"中的每次执行都会耽搁一段时间。

我们需要先选中Sequence节点的装饰器然后设置"通知观察者"为"结果改变时","观察器中止"为"self",表示当黑板键"Target Character"改变时就中止Sequence执行回到Selector。

同样的,当NPC跟随玩家时失去感知后也应该中止跟随。

五、优化NPC速度
下面我们希望实现的功能是NPC在巡逻时的速度是缓慢的,发现玩家后跟随的速度要更快一些。
有两种方法,一种是我们可以在行为树中新建一个任务来设置NPC的速度,还有一种方法是通过新建服务实现,这里使用第2中方法。
- 点击"新建服务"

这里服务命名为"BTService_SetLionSpeed",表示用于设置狮子的速度

打开"BTService_SetLionSpeed",在事件图表中添加如下节点来修改狮子的行走速度

设置变量"MaxSpeed"为可编辑实例

- 回到行为树"BT_Lion",右键点击Sequence选择"添加服务-》BTService_SetLionSpeed"

选中服务"BTService_SetLionSpeed",在细节面板中设置"MaxSpeed"的值,这里设置为120。这样当狮子巡逻时的速度就是120

同样的方法设置狮子在跟踪时的速度为600

此时运行效果如下
