How to spawn actors at edge of viewport?

Hi guys, I would like to drop here my solution. 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. 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.

With this you can check if any of your actors are outside of the rectangle bounds on it’s plane at any given distance from camera.

void AiCameraActor::GetViewportSizedRectAtDistance( FVector OutputArr[], float Distance = 100.0f, float HorizontalOffset = 0.0f, float VerticalOffset = 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);
	const float HalfHorizontalFOVInRadians = FMath::DegreesToRadians( Info.FOV * 0.5f );
	float FrustumAspectRatio = Info.bConstrainAspectRatio ? Info.AspectRatio : ViewportSize.X / ViewportSize.Y;
	float HozLength = 0.0f;
	float VertLength = 0.0f;

	HozLength = Distance * FMath::Tan(HalfHorizontalFOVInRadians) + HorizontalOffset;
	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;
}