自定义行为树任务
2023年10月29日 2023年11月17日
生成随机点, 并设置到黑板变量
说明
- 派生自C++类BTTaskNode
- 依赖模块
GameplayTasks
和NavigationSystem
在构造函数中设置任务名
STUNextLocationTask
1USTUNextLocationTask::USTUNextLocationTask() 2{ 3 NodeName = "Next Location"; 4}
任务逻辑
原型
1virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory);
返回值
- 成功
1return EBTNodeResult::Succeeded;
- 失败
1return EBTNodeResult::Failed;
生成随机点
1#include "AIController.h" 2#include "NavigationSystem.h" 3 4const auto Controller = OwnerComp.GetAIOwner(); 5if (!Controller) return EBTNodeResult::Failed; 6 7const auto Pawn = Controller->GetPawn(); 8if (!Pawn) return EBTNodeResult::Failed; 9 10const auto NavSys = UNavigationSystemV1::GetCurrent(Pawn); 11if (!NavSys) return EBTNodeResult::Failed; 12 13FNavLocation NavLocation; 14const auto Found = NavSys->GetRandomReachablePointInRadius(Pawn->GetActorLocation(), 1000, NavLocation); 15if (!Found) return EBTNodeResult::Failed;
设置黑板变量
- 添加属性: 存放黑板变量信息
1UPROPERTY(EditAnywhere, BlueprintReadWrite) 2FBlackboardKeySelector AimLocationKey;
- 设置黑板变量
1#include "BehaviorTree/BlackboardComponent.h" 2 3const auto Blackboard = OwnerComp.GetBlackboardComponent(); 4if (!Blackboard) return EBTNodeResult::Failed; 5Blackboard->SetValueAsVector(AimLocationKey.SelectedKeyName, NavLocation.Location);
完整实现
1#include "BehaviorTree/BlackboardComponent.h" 2#include "AIController.h" 3#include "NavigationSystem.h" 4 5EBTNodeResult::Type USTUNextLocationTask::ExecuteTask(UBehaviorTreeComponent &OwnerComp, uint8 *NodeMemory) 6{ 7 const auto Controller = OwnerComp.GetAIOwner(); 8 const auto Blackboard = OwnerComp.GetBlackboardComponent(); 9 if (!Controller || !Blackboard) return EBTNodeResult::Failed; 10 11 const auto Pawn = Controller->GetPawn(); 12 if (!Pawn) return EBTNodeResult::Failed; 13 14 const auto NavSys = UNavigationSystemV1::GetCurrent(Pawn); 15 if (!NavSys) return EBTNodeResult::Failed; 16 17 FNavLocation NavLocation; 18 const auto Found = NavSys->GetRandomReachablePointInRadius(Pawn->GetActorLocation(), 1000, NavLocation); 19 if (!Found) return EBTNodeResult::Failed; 20 21 Blackboard->SetValueAsVector(AimLocationKey.SelectedKeyName, NavLocation.Location); 22 return EBTNodeResult::Succeeded; 23}
在行为树中使用该任务
添加黑板变量
BB_STUCharacter
设置行为树
-
添加节点:
Next Location
; 设置待设置黑板变量 -
添加节点:
Move To
; 设置目的黑板变量 -
完整行为树