Search code examples
c++unreal-engine4

Referencing pawn player in c++ ue4


for a project i am designing a tank game and want a tank to be constantly looking at my player but after looking online a lot i haven't found a solution to referencing my player in c++

 ATank* myCharacter = Cast<ATank>(this);

     if (myCharacter)
     {
         FVector targetLocation = myCharacter->GetActorLocation();
         FVector myLocation = GetActorLocation();

         FRotator newrot = (myLocation -targetLocation).Rotation();

         NewRotation.Yaw = newrot.Yaw;
         SetActorRotation(NewRotation);
     }

above is what i have at the moment which does nothing as its not finding the player and before i put the if statement in it was just crashing, any help/guidance is appreciated and thanks in advance.


Solution

  • You can use UGameplayStatics::GetPlayerPawn(...) UE Docs and each ATank can hold it's reference to your pawn. Then you should check if your stored reference is not null and IsValidLowLevel(). Next step is to perform desired computations using player pawn reference.