Download

Top down Mouse Based Look/Aiming help needed

Hey guys could anyone help me out solving the issue I am having with my aiming/rotation system.

What I am trying to implement is player rotation that is is dictated by the location the mouse is on the screen, so far the problems I am having is

  1. Rotation speed seems amplified the closer to the player the mouse is
  2. Player is not able to rotate past 180 degrees (can rotate in special circumstances)
  3. Player does rotate with mouse move but it does not look at the mouse location rather just turns in the way the mouse goes.

Here is my code and a video, Note I’m rendering a decal to mouse position for testing purposes.
https://vid.me/k2d8



void AOpCharacter::Tick(float DeltaSeconds)
{

	if (CursorToWorld != nullptr)
	{
		if (APlayerController* PC = Cast<APlayerController>(GetController()))
		{
			FHitResult TraceHitResult;
			PC->GetHitResultUnderCursor(ECC_Visibility, true, TraceHitResult);
			FVector CursorFV = TraceHitResult.ImpactNormal;
			FRotator CursorR = CursorFV.Rotation();
			CursorToWorld->SetWorldLocation(TraceHitResult.Location);
			CursorToWorld->SetWorldRotation(CursorR);

		}
		AOpCharacter::SetLookDirection();	
	}
}



void AOpCharacter::SetLookDirection()
{
	APlayerController* PlayerController = Cast<APlayerController>(GetController());
	if (PlayerController != nullptr)
	{
		float LocationX;
		float LocationY;

		FVector2D MousePosition(LocationX, LocationY);

		FHitResult HitResult;
		const bool bTraceComplex = false;

		PlayerController->GetHitResultAtScreenPosition(MousePosition, ECC_Visibility, bTraceComplex, HitResult);

		FVector CharLocation = this->GetActorLocation();
		FVector2D CharRelScreen;
		PlayerController->ProjectWorldLocationToScreen(CharLocation, CharRelScreen); 

		// Calculate Mouse position relative to Character
		FVector2D CharActual;
		CharActual.X = - (MousePosition.Y - CharRelScreen.Y);
		CharActual.Y = MousePosition.X - CharRelScreen.X;

		float RotationAngle = FMath::RadiansToDegrees(FMath::Acos(CharActual.X / CharActual.Size()));

		if (CharActual.Y < 0)
			RotationAngle = 360 - RotationAngle;

		FRotator rotation(0, FMath::Clamp(RotationAngle, -360.f, 360.f), 0);

		this->SetActorRotation(rotation);
	}
}


If you can help it would be Greatly appreciated Thanks!

edit: Thanks if you where interested in helping, I managed to fix it. Seems a defult setting was conflicting with my mouse movement.

I’d like to know how to do this with blue prints right now my character turns and moves with “wasd” and snaps to the mouse when I right click. I want the character to always be following the mouse