Created
May 28, 2019 16:37
-
-
Save whoo24/09324dcff276e0247f18fd12005ebcfb to your computer and use it in GitHub Desktop.
Get Actor Position in Screen space in UE4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It works really well, thanks!!
I needed to change
Actor&
toActor*
to compile it. You can consider to fix it: