[SOLVED] Mouse location to world space

Or, because handling gameplay mechanics like input through the HUD is pants-on-head-pencils-up-the-nose retarded, you could use this code in your own project to give you projection / deprojection functions you can use from anywhere:


FVector UMyGameplayStatics::Project(UObject* WorldContextObject, FVector Location)
{
	FPlane V(0, 0, 0, 0);
	UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject);
	ULocalPlayer* LocalPlayer = GEngine->GetLocalPlayerFromControllerId(World, 0);

	FSceneViewFamilyContext ViewFamily(FSceneViewFamily::ConstructionValues(LocalPlayer->ViewportClient->Viewport, World->Scene, LocalPlayer->ViewportClient->EngineShowFlags).SetRealtimeUpdate(true));

	FVector OutViewLocation;
	FRotator OutViewRotation;
	FSceneView* SceneView = LocalPlayer->CalcSceneView(&ViewFamily, OutViewLocation, OutViewRotation, LocalPlayer->ViewportClient->Viewport);

	if (SceneView != NULL)
	{
		Location.DiagnosticCheckNaN();
		V = SceneView->Project(Location);
	}

	FVector2D ScreenDimensions;
	LocalPlayer->ViewportClient->GetViewportSize(ScreenDimensions);

	FVector resultVec(V);
	resultVec.X = (ScreenDimensions.X / 2.f) + (resultVec.X*(ScreenDimensions.X / 2.f));
	resultVec.Y *= -1.f * GProjectionSignY;
	resultVec.Y = (ScreenDimensions.Y / 2.f) + (resultVec.Y*(ScreenDimensions.Y / 2.f));

	// if behind the screen, clamp depth to the screen
	if (V.W <= 0.0f)
	{
		resultVec.Z = 0.0f;
	}
	return resultVec;
}

void UMyGameplayStatics::Deproject(UObject* WorldContextObject, FVector2D ScreenPos, /*out*/ FVector& WorldOrigin, /*out*/ FVector& WorldDirection)
{
	UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject);
	ULocalPlayer* LocalPlayer = GEngine->GetLocalPlayerFromControllerId(World, 0);

	FSceneViewFamilyContext ViewFamily(FSceneViewFamily::ConstructionValues(
		LocalPlayer->ViewportClient->Viewport,
		World->Scene,
		LocalPlayer->ViewportClient->EngineShowFlags)
		.SetRealtimeUpdate(true));

	FVector OutViewLocation;
	FRotator OutViewRotation;
	FSceneView* SceneView = LocalPlayer->CalcSceneView(&ViewFamily, OutViewLocation, OutViewRotation, LocalPlayer->ViewportClient->Viewport);

	if (SceneView != NULL)
	{
		SceneView->DeprojectFVector2D(ScreenPos, /*out*/ WorldOrigin, /*out*/ WorldDirection);
	}
}

2 Likes