Hello friends,
I need to rotate my player towards the point the mouse is targeting so I have written the following code:
void ALeviathanPlayerController::RotateToTarget()
{
APawn* thePawn = GetControlledPawn();
if (thePawn)
{
if (IsLocalPlayerController())
{
FVector2D mousePosition = FVector2D(0, 0);
GetMousePosition(mousePosition.X, mousePosition.Y);
FVector worldLocation = thePawn->GetActorLocation();
FVector targetLocation, targetDirection;
DeprojectScreenPositionToWorld(mousePosition.X, mousePosition.Y, targetLocation, targetDirection);
DrawDebugLine(GetWorld(), targetLocation, targetDirection, FColor::Red);
targetDirection *= 10000;
targetDirection += targetLocation;
FVector Intersection = FMath::LinePlaneIntersection(targetLocation, targetDirection, thePawn->GetActorLocation(), FVector(0, 0, 1));
FRotator Rotation = FRotationMatrix::MakeFromX(Intersection).Rotator();
thePawn->SetActorRotation(Rotation);
}
}
}
The character rotates but as well as all other characters, even though I checked if it’s a local player controller. And it’s happening really fast and doesn’t work.
I’ve setup the following in Blueprints and it works perfectly fine. Recreating the same thing doesn’t seem to work in C++.
Here’s the BP script: