Download

Enemy Running Direction C++ Top Down Template

My enemies are following me but they are facing the wrong direction. How do I get them to face the direction they are running?


// Called every frame
void AMonster::Tick( float DeltaTime )
{
	Super::Tick( DeltaTime );

	ACharacter *avatar = Cast<ACharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
	if (!avatar) return;
	FVector toPlayer = avatar->GetActorLocation() -	GetActorLocation();
	
	this->GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to moving direction
	//GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f);
	float distanceToPlayer = toPlayer.Size();
	// If the player is not in the SightSphere of the monster,
	// go back
	if (distanceToPlayer > SightSphere->GetScaledSphereRadius())
	{
		// If the player is out of sight,
		// then the enemy cannot chase
		return;
	}
	toPlayer /= distanceToPlayer; // normalizes the vector
	// Actually move the monster towards the player a bit
	AddMovementInput(toPlayer, Speed * DeltaTime);
	// At least face the target
	// Gets you the rotator to turn something
	// that looks in the `toPlayer` direction
	FRotator toPlayerRotation = toPlayer.Rotation();
	toPlayerRotation.Pitch = 0; // 0 off the pitch
	RootComponent->SetWorldRotation(toPlayerRotation);
}

Thanks in advance :slight_smile:

Solution:

Rotate the mesh so it faces the capsules look vector :p. In my case I had to rotate it -90 degrees