Convert Blueprint Node "AIMoveTo" to C++ code

So I’m working On a Tower Defense Game, the original version of this was implemented by pure Blueprint. However, here comes the problem.
In the original version, I have some waypoints to tell the Enemy where to go like this


every waypoint stored a pointer that contained the next waypoint to go
image
once the Enemy reached a waypoint it will automatically go to the next waypoint, in Blueprint I do this thing this way

but in C++ I don’t know how to use “AIMoveTo”, I can only use MoveToActor or MoveToLocation and so on like this
CPP

if (EnemyAIController)
	{
		if(NextPosition)
		{
			do
			{
				EnemyAIController->MoveToActor(NextPosition, 5.0f, false);
				NextPosition = NextPosition->NextPosition;
			} while (NextPosition);
		}

	}

But the problem is that after the EnemyAIController->MoveToActor(NextPosition, 5.0f, false); executed, the Enemy is still on the way to First Waypoint, but the NextPosition = NextPosition->NextPosition; even the entire do-while loop has already been executed, so the Enemy just walk directly to the last waypoint instead of one by one. So I wonder if there is any way to do this in C++ as I did in Blueprint?

This will execute continuously as if you’re executing from the normal pin of
image

You’d want to either find a way to have a delegate that will get called when your AI reaches it’s destination, possibly not using do-while.

2 Likes

Ok, so after another search, I found a function in AAIController named OnMoveCompleted, all I need to do is to create a class that inherited from AAIController and override this function like this

void AEnemyAIController::OnMoveCompleted(FAIRequestID RequestID, const FPathFollowingResult& Result)
{
	Super::OnMoveCompleted(RequestID, Result);

	Enemy = Cast<AEnemy>(GetPawn());

	if(Enemy)
	{
		if (Enemy->NextPosition->NextPosition)
		{
			Enemy->NextPosition = Enemy->NextPosition->NextPosition;
			Enemy->Move();
		}
	}
}

and this is my AEnemy::Move() function

void AEnemy::Move()
{
	if (StartPosition)
	{
		NextPosition = StartPosition->FirstPosition;
		StartPosition = nullptr;
		GetWorldTimerManager().ClearTimer(WaitForStartTimerHandle);
	}
	if (EnemyAIController)
	{
		if (NextPosition)
		{
			EnemyAIController->MoveToActor(NextPosition, 5.0f, false);
		}
	}
}

After the first time I call EnemyAIController->MoveToActor(NextPosition, 5.0f, false); the OnMoveCompleted will automatically be called After the move completed, which behaves exactly like that Blueprint version.