Hi, I am trying to make Patroling AI that will be moving to the target points. I was taking steps from a tutorial on Udemy, but it doesn’t move. I tried NavSysPathsUpdate.py to update my code, now it runs without errors but still doesn’t move.
#include "AIEnemy.h"
#include "Perception/PawnSensingComponent.h"
#include "DrawDebugHelpers.h"
#include "PavorGameMode.h"
#include "TimerManager.h"
#include "NavigationSystem.h"
// Sets default values
AAIEnemy::AAIEnemy()
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
PawnSensingComp = CreateDefaultSubobject<UPawnSensingComponent>(TEXT("PawnSensingComp"));
PawnSensingComp->OnSeePawn.AddDynamic(this, &AAIEnemy::OnPawnSeen);
PawnSensingComp->OnHearNoise.AddDynamic(this, &AAIEnemy::OnNoiseHeard);
}
// Called when the game starts or when spawned
void AAIEnemy::BeginPlay()
{
Super::BeginPlay();
OriginalRotation = GetActorRotation();
if (bPatrol)
{
MoveToNextPatrolPoint();
}
}
void AAIEnemy::OnPawnSeen(APawn * SeenPawn)
{
if (SeenPawn == nullptr)
{
return;
}
DrawDebugSphere(GetWorld(), SeenPawn->GetActorLocation(), 32.0f, 12, FColor::Red, false, 10.0f);
APavorGameMode* GM = Cast<APavorGameMode>(GetWorld()->GetAuthGameMode());
if (GM)
{
GM->CompleteMission(SeenPawn, false);
}
AController* Controller = GetController();
if (Controller)
{
Controller->StopMovement();
}
}
void AAIEnemy::OnNoiseHeard(APawn * NoiseInstigator, const FVector & Location, float Volume)
{
DrawDebugSphere(GetWorld(), Location, 32.0f, 12, FColor::Green, false, 10.0f);
FVector Direction = Location - GetActorLocation();
Direction.Normalize();
FRotator NewLookAt = FRotationMatrix::MakeFromX(Direction).Rotator();
NewLookAt.Pitch = 0.0f;
NewLookAt.Roll = 0.0f;
SetActorRotation(NewLookAt);
GetWorldTimerManager().ClearTimer(TimerHandle_ResetOrientation);
GetWorldTimerManager().SetTimer(TimerHandle_ResetOrientation, this, &AAIEnemy::ResetOrientation, 3.0f);
AController* Controller = GetController();
if (Controller)
{
Controller->StopMovement();
}
}
void AAIEnemy::ResetOrientation()
{
SetActorRotation(OriginalRotation);
if (bPatrol)
{
MoveToNextPatrolPoint();
}
}
// Called every frame
void AAIEnemy::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
//Patrol Goal Checks
if (CurrentPatrolPoint)
{
FVector Delta = GetActorLocation() - CurrentPatrolPoint->GetActorLocation();
float DistanceToGoal = Delta.Size();
// Check if we are within 50 units of our goal, if so - pick a new patrol point
if (DistanceToGoal < 50)
{
MoveToNextPatrolPoint();
}
}
}
void AAIEnemy::MoveToNextPatrolPoint()
{
// Assign next patrol point
if (CurrentPatrolPoint == nullptr || CurrentPatrolPoint == SecondPatrolPoint)
{
CurrentPatrolPoint = FirstPatrolPoint;
}
else
{
CurrentPatrolPoint = SecondPatrolPoint;
}
UNavigationSystemV1::SimpleMoveToActor(GetController(), CurrentPatrolPoint);
}