As a beginner who downloaded UE4 for less than two weeks, I had a lot of trouble finding the right solution
of how to rotate a character so that it faces the cursor(in a top down game), I feel like such basic operation should not
be a struggle to do. But anyway it may just be me lacking the google skill… Enjoy!
Edit: The code below is working ! I just wanna share my solution.
[TABLE]
void ATdCharacter::SetCursorDir() {
//note that the line 58-59 is seen pretty common on the internet to find the cursor porjection
//onto the internet, however, they do not give me the right vector.
//FVector CursorWorldLocation, CursorWorldDirection;
//GetWorld()->GetFirstPlayerController()->DeprojectMousePositionToWorld(CursorWorldLocation, CursorWorldDirection);
//=====================================================================//
//gets location of the actor in the world
FVector CurrLoc = this->GetActorLocation();
// the right method of getting cursor location!!! note: i used the exact same method in the Epic Top Down Blueprint.
FHitResult hitResult;
GetWorld()->GetFirstPlayerController()->GetHitResultUnderCursorByChannel(UEngineTypes::ConvertToTraceType(ECC_Visibility), true,hitResult);
FVector hitLoc = hitResult.Location;
//geting the original rotation of the acter;
FRotator newRot = this->GetActorRotation();
//Using atan2 function to get the degree between our character location and cursor location
// aka how much we want the character to rotate
float newYaw = (hitLoc - CurrLoc).Rotation().Yaw;;
//Using that degree as the Yaw(rotating around Z axis) of our Frotator
newRot.Yaw = newYaw;
//in the end, we set it;
this->GetController()->SetControlRotation(newRot);
}
the complete code to class can be found on my github: GitHub - trazd66/Source: The right way to setup a cursor-facing character in UE4 with C++