本篇文章的目的:在UE4中使用C++实现一个自己的行为树任务节点。该任务节点可以完成简单的朝向Actor移动的功能。
版本号:4.26
项目名:AITest
第一步,新建一个C++类,继承自BTTask_BlackboardBase,命名为BTTask_MyMoveTo。
出现提示:
需要在AITest.Build.cs中,修改下面这行代码,添加 “GameplayTasks”。
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "HeadMountedDisplay", "GameplayTasks" });
第二步:编写代码
BTTask_MyMoveTo.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "BehaviorTree/Tasks/BTTask_BlackboardBase.h"
#include "BTTask_MyMoveTo.generated.h"
/**
*
*/
UCLASS()
class AITEST_API UBTTask_MyMoveTo : public UBTTask_BlackboardBase
{
GENERATED_BODY()
public:
UBTTask_MyMoveTo();
virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override;
#if WITH_EDITOR
virtual FName GetNodeIconName() const override;
#endif // WITH_EDITOR
};
BTTask_MyMoveTo.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "BTTask_MyMoveTo.h"
#include "BehaviorTree/Blackboard/BlackboardKeyType_Object.h"
#include "AIController.h"
#include "BehaviorTree/BlackboardComponent.h"
UBTTask_MyMoveTo::UBTTask_MyMoveTo()
{
NodeName = "MyMoveTo";
BlackboardKey.AddObjectFilter(this, GET_MEMBER_NAME_CHECKED(UBTTask_MyMoveTo, BlackboardKey), AActor::StaticClass());
}
EBTNodeResult::Type UBTTask_MyMoveTo::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
AAIController* AIController = Cast<AAIController>(OwnerComp.GetAIOwner());
UBlackboardComponent* MyBlackboard = OwnerComp.GetBlackboardComponent();
UObject* KeyValue = MyBlackboard->GetValue<UBlackboardKeyType_Object>(BlackboardKey.GetSelectedKeyID());
AActor* TargetActor = Cast<AActor>(KeyValue);
if (TargetActor)
{
AIController->MoveToActor(TargetActor, 50.0f);
return EBTNodeResult::Succeeded;
}
return EBTNodeResult::Failed;
}
#if WITH_EDITOR
FName UBTTask_MyMoveTo::GetNodeIconName() const
{
return FName("BTEditor.Graph.BTNode.Task.MoveTo.Icon");
}
#endif // WITH_EDITOR
第三步,就可以直接投入使用了。
在AIController中运行行为树,将玩家Actor传给Player。
再将MyMoveTo中的黑板键值改为Player。
然后编辑器运行。
需要注意的是:你要让AI跑起来,需要:AI角色蓝图,AI控制器蓝图,行为树,黑板,导航体积等东西。但这些是蓝图基础,所以这里就不写了。