Method to get vertices of camera rectangle viewport in world space suggestion

Hi guys, I would like to drop here my solution to often asked questoin about getting vieport bounds in world space. Below method calculates four vertices of camera facing rectangle in world space, that is aligned with viewport edges and fills it entirely. You can specify distance at which you would like to have your rectangle calculated, it’s size wil be adjusted so that it always fills viewport. I’ve added this method to my camera actor.

The default distance of 100u is the currently predefined distance of near clipping plane. Offsets allow to scale rectangle, which helped me to get rectangle slightly bigger than viewport, which I needed to safely fit backgrounds of my 2d game within viewport.

Is this safe to use? I’ve already noticed that GetViewportSize might return zero vector if called before viewport is fully initialised.



voidAiCameraActor::GetViewportSizedRectAtDistance( FVectorOutputArr], floatDistance = 100.0f, floatHorizontalOffset = 0.0f, floatVerticalOffset = 0.0f )
{
FMinimalViewInfo Info = FMinimalViewInfo();
GetCameraComponent()->GetCameraView( GetWorld()->GetDeltaSeconds(), Info );
FVector LeftVector( 0.0f, -1.0f, 0.0f );
FVector UpVector( 0.0f, 0.0f, 1.0f );
FVector LookDirection = Info.Rotation.Vector();
LookDirection.Normalize();
FVector2D ViewportSize = FVector2D( 0.f, 0.f );
GEngine->GameViewport->GetViewportSize(ViewportSize);
constfloat HalfHorizonFOVInRadians = FMath::DegreesToRadians( Info.FOV * 0.5f );
float FrustumAspectRatio = Info.bConstrainAspectRatio ? Info.AspectRatio : ViewportSize.X / ViewportSize.Y;

float HozLength = Distance * FMath::Tan(HalfHorizonFOVInRadians) + HorizontalOffset;
float VertLength = HozLength / FrustumAspectRatio + VerticalOffset;

FVector ViewportWorldCetnter = Info.Location + LookDirection * Distance;
FVector LeftLength = LeftVector * HozLength;
FVector UpLength = UpVector * VertLength;

OutputArr[0] = ViewportWorldCetnter - UpLength - LeftLength;
OutputArr[1] = ViewportWorldCetnter - UpLength + LeftLength;
OutputArr[2] = ViewportWorldCetnter + UpLength + LeftLength;
OutputArr[3] = ViewportWorldCetnter + UpLength - LeftLength;
}


1 Like