Skip to content

Instantly share code, notes, and snippets.

@whoo24
Created May 28, 2019 16:37
Show Gist options
  • Save whoo24/09324dcff276e0247f18fd12005ebcfb to your computer and use it in GitHub Desktop.
Save whoo24/09324dcff276e0247f18fd12005ebcfb to your computer and use it in GitHub Desktop.
Get Actor Position in Screen space in UE4
bool GetActorPosInScreenSpace(const APlayerController* Player, const AActor& Actor, FVector2D& OutScreenPos)
{
FVector WorldPosition = Actor->GetActorLocation();
ULocalPlayer* const LP = Player ? Player->GetLocalPlayer() : nullptr;
if (LP && LP->ViewportClient)
{
// get the projection data
FSceneViewProjectionData ProjectionData;
if (LP->GetProjectionData(LP->ViewportClient->Viewport, eSSP_FULL, /*out*/ ProjectionData))
{
FMatrix const ViewProjectionMatrix = ProjectionData.ComputeViewProjectionMatrix();
const bool bResult = FSceneView::ProjectWorldToScreen(WorldPosition, ProjectionData.GetConstrainedViewRect(), ViewProjectionMatrix, OutScreenPos);
FPlane Result = ViewProjectionMatrix.TransformFVector4(FVector4(WorldPosition, 1.f));
if (Result.W > 0.0f)
{
// the result of this will be x and y coords in -1..1 projection space
const float RHW = 1.0f / Result.W;
FPlane PosInScreenSpace = FPlane(Result.X * RHW, Result.Y * RHW, Result.Z * RHW, Result.W);
OutScreenPos = FVector2D{ PosInScreenSpace.X, PosInScreenSpace.Y };
return true;
}
}
}
OutScreenPos = FVector2D::ZeroVector;
return false;
}
@AndreaCatania
Copy link

It works really well, thanks!!
I needed to change Actor& to Actor* to compile it. You can consider to fix it:

-bool GetActorPosInScreenSpace(const APlayerController* Player, const AActor& Actor, FVector2D& OutScreenPos)
+bool GetActorPosInScreenSpace(const APlayerController* Player, const AActor* Actor, FVector2D& OutScreenPos)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment