- From the Content Browser, select Add New | New C++ Class. From the Choose Parent Class menu, check the Show All Classes option and look for the BTTask_BlackboardBase class. Select it and then hit the Next button:
- At the next menu, set its name to BTTask_MoveToPlayer and then click on the Create Class option:
- Open Visual Studio and add the following function to BTTask_MoveToPlayer.h:
#pragma once
#include "CoreMinimal.h"
#include "BehaviorTree/Tasks/BTTask_BlackboardBase.h"
#include "BTTask_MoveToPlayer.generated.h"
/**
*
*/
UCLASS()
class CHAPTER_13_API UBTTask_MoveToPlayer : public UBTTask_BlackboardBase
{
GENERATED_BODY()
public:
/** starts this task, should return Succeeded, Failed or InProgress
* (use FinishLatentTask() when returning InProgress)
* this function should be considered as const (don't modify state of object) if node is not instanced! */
virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override;
};
- Then, open the BTTask_MoveToPlayer.cpp file and update it to the following:
#include "BTTask_MoveToPlayer.h"
#include "EnemyAIController.h"
#include "GameFramework/Character.h"
#include "BehaviorTree/Blackboard/BlackboardKeyType_Object.h"
EBTNodeResult::Type UBTTask_MoveToPlayer::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
auto EnemyController = Cast<AEnemyAIController>(OwnerComp.GetAIOwner());
auto Blackboard = OwnerComp.GetBlackboardComponent();
ACharacter * Target = Cast<ACharacter>(Blackboard->GetValue<UBlackboardKeyType_Object>(EnemyController->TargetKeyID));
if(Target)
{
EnemyController->MoveToActor(Target, 50.0f);
return EBTNodeResult::Succeeded;
}
return EBTNodeResult::Failed;
}
- Save your files and return to the Unreal Editor. Compile your code.
- In the Content Browser, go to the Content folder where the EnemyBehaviorTree we created previously is located and double-click on it to open the Behavior Tree editor.
- Drag this below the Selector node and select Tasks | Move to Player:
- Save the Behavior Tree and return to the Unreal Editor. Drag and drop a MyEnemyCharacter object into the scene if you haven't done so already and play the game:
As you can see, our enemy is now following our player, which will happen for as long as the NavMesh covers the area!