Im on lecture 173 of the course and my enemies will not MoveToTarget on being play when calling that function. Ican get them to move to target on begin play if i use the GetWorldTimeManager peice of code, i can alos get them to MoveToTarget if i put that function in tick instead.
But when trying to put MoveToTarget in begin play and then use GetWorldTimeManager function in tick my enemies will not start moving to the target on begin play therefore my timer function in tick is rendered useless. Here is my code that will not get them to move.
void AEnemy::PatrolTimerFinished()
{
MoveToTarget(PatrolTarget);
}
void AEnemy::BeginPlay()
{
Super::BeginPlay();
if (HealthBarWidget)
{
HealthBarWidget->SetVisibility(false);
}
EnemyController = Cast<AAIController>(GetController());
MoveToTarget(PatrolTarget);
}
bool AEnemy::InTargetRange(AActor* Target, double Radius)
{
if (Target == nullptr) return false;
const double DistanceToTarget = (Target->GetActorLocation() - GetActorLocation()).Size();
DRAW_SPHERE_SingleFrame(GetActorLocation());
DRAW_SPHERE_SingleFrame(Target->GetActorLocation());
return DistanceToTarget<= Radius;
}
void AEnemy::MoveToTarget(AActor* Target)
{
if (EnemyController == nullptr || Target == nullptr) return;
FAIMoveRequest MoveRequest;
MoveRequest.SetGoalActor(Target);
MoveRequest.SetAcceptanceRadius(15.f);
EnemyController->MoveTo(MoveRequest);
}
AActor* AEnemy::ChoosePatrolTarget()
{
TArray<AActor*> ValidTargets;
for (AActor* Target : PatrolTargets)
{
if (Target != PatrolTarget)
{
ValidTargets.AddUnique(Target);
}
}
const int32 NumPatrolTargets = ValidTargets.Num();
if (NumPatrolTargets > 0)
{
const int32 TargetSelection = FMath::RandRange(0, NumPatrolTargets - 1);
return ValidTargets[TargetSelection];
}
return nullptr;
}
void AEnemy::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
CheckCombatTarget();
CheckPatrolTarget();
}
void AEnemy::CheckPatrolTarget()
{
if (InTargetRange(PatrolTarget, PatrolRadius))
{
PatrolTarget = ChoosePatrolTarget();
GetWorldTimerManager().SetTimer(PatrolTimer, this, &AEnemy::PatrolTimerFinished, 3.f);
}
}
void AEnemy::CheckCombatTarget()
{
if (!InTargetRange(CombatTarget, CombatRadius))
{
CombatTarget = nullptr;
if (HealthBarWidget)
{
HealthBarWidget->SetVisibility(false);
}
}
}