How to do it...

  1. 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:

  1. At the next menu, set its name to BTTask_MoveToPlayer and then click on the Create Class option:

  1. 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;

};

  1. 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;
}
  1. Save your files and return to the Unreal Editor. Compile your code.
  2. In the Content Browsergo to the Content folder where the EnemyBehaviorTree we created previously is located and double-click on it to open the Behavior Tree editor.
  1. Drag this below the Selector node and select Tasks | Move to Player:

  1. 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!