1. 程式人生 > >UE4 AIController 尋路

UE4 AIController 尋路

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "AIController.h"
#include "EnemyCharacter.h"
#include "EnemyAIController.generated.h"

/**
 * 在介面-體積-NavMeshBoundsVolume(導航網格) ,拖到場景中設定,按下P鍵顯示
   在ProjectSetting的NavigationMesh-Generation-CellSize和Cellheight 設定值
 */
UCLASS()
class PACMAN_API AEnemyAIController : public AAIController
{
	GENERATED_BODY()

public:
		//要重寫的函式
	//相當於beginplay,每當開啟一個ai的時候,首先執行Possess
	void Possess(APawn* InPawn)override;
	//移動停止後呼叫
	virtual void OnMoveCompleted(FAIRequestID RequestID,const FPathFollowingResult& Result)override;


	void SearchNewPoint();

	void StopMove();

private:
	AEnemyCharacter * Bot;

};

 

// Fill out your copyright notice in the Description page of Project Settings.

#include "EnemyAIController.h"
#include "AI/Navigation//NavigationSystem.h"

void AEnemyAIController::Possess(APawn * InPawn)
{
	Super::Possess(InPawn);
	Bot = Cast<AEnemyCharacter>(InPawn);
	SearchNewPoint();

}

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

void AEnemyAIController::SearchNewPoint()
{
	//通過導航網格來實現
	//獲取導航系統
	UNavigationSystem* NavMesh = UNavigationSystem::GetCurrent(this);
	if (NavMesh){
		//搜尋半徑
		const float SearchRadius = 1000.0f;
		FNavLocation RandomPt;

		//返回是否能找到
	const bool bFound=NavMesh->GetRandomReachablePointInRadius(Bot->GetActorLocation(), SearchRadius, RandomPt);
	if (bFound)
	{
		//移動到找到的點
		MoveToLocation(RandomPt);
	}
	}
}

void AEnemyAIController::StopMove()
{
	//停止移動
	StopMovement();
}