Converting World coordinates to Viewport in split screen
Hello,
I am coding an edge screen radar for offscreen targets. It works perfectly fine with a single camera that's taking up the whole screen with the default viewport values (0, 0, 1, 1).
My problem is that I want to use this in a split screen configuration with each player having their own camera and therefore, own radar. The cameras have different viewport values to achieve that split screen, for example, the bottom right one has a ViewportRect of (0.5, 0, 0.5, 0.5).
I am using WorldToScreenPoint to convert the target's world position to a position on the screen to compute my arrow position, but since that gives me a screen position, my arrows are on the whole screen and not just limited to one camera.
Is there an equivalent to WorldToScreenPoint, or WorldToViewportPoint to convert the position to the actual camera viewport and not the whole screen?
Hi there Did you find a solution to this? I can’t get it working either
I most likely have, but I can't remember as that was a couple years ago and I don't have access to the repo anymore, sorry. :|
Answer by Hellium · Apr 13, 2018 at 10:13 AM
You can use the viewport position to make sure the object is not outside the viewfrustum of your camera, thus, preventing your UI element to go outside of the viewport of the player's camera:
private void LateUpdate()
{
Vector3 viewportPos = playerCamera.WorldToViewportPoint( target.position );
if( viewportPos.x >= 0 && viewportPos.x <= 1 && viewportPos.y >=0 && viewportPos.y <= 1 )
rectTransform.anchoredPosition = playerCamera.WorldToScreenPoint( target.position );
}