Problem with tracing from screen to world

Hello friends

I’ve made my prototype game in Blueprints but I want to make it C++ now and so far everything is good but there’s a problem with tracing from screen to world. Here’s my code:

Solution #1:

void ALeviathanPlayerController::RotateToTarget()
{
	APawn* thePawn = GetControlledPawn();
	
	if (thePawn)
	{
		if (IsLocalPlayerController())
		{
			FVector2D mousePosition = FVector2D(0, 0);
			GetMousePosition(mousePosition.X, mousePosition.Y);

			FVector worldLocation = GetCharacter()->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);

			this->SetControlRotation(Rotation);
		}
	}
}

That didn’t work, so I tried another solution:

Solution #2:

/*
	FHitResult Hit;
	GetHitResultUnderCursor(ECC_Camera, false, Hit);

	FRotator Rot = FRotationMatrix::MakeFromX(Hit.ImpactPoint).Rotator();

	SetControlRotation(Rot);
	*/

It rotates the character, but as the player walks it start rotating in the wrong direction. I don’t know how to fix it. Any ideas?