WorldToScreenPoint on multiple screens (split screen)

Hey I have this split screen game where the player have the life bar and player name over their player character, how can I use WorldToScreenPoint with multiple cameras? its seems the life bar only work on the first player camera and the other player see ghost life bars floating around lol as if the first camera occupied the whole screen.

I think your looking to use the WorldToViewPortPoint method instead :slight_smile: This will position it within the viewport for each camera instead of within the entire screen area.
Here is the doc’s: Unity - Scripting API: Camera.ViewportToWorldPoint

1 Like

Hey thanks a lot this is exactly what I was looking for.

can anyone explain a little bit more how to use this, I have been trying for hours but the GUI keeps drawing outside the camera.
this is an extract of the code I have right now:

Vector3 ViewPortPos = Camera.main.WorldToViewportPoint(PlayerCharacter.transform.position);
        Vector3 screenPos = Camera.main.ViewportToScreenPoint(ViewPortPos);
        x = screenPos.x - xOffset; // x offset
        y = screenPos.y - yOffset; // y offset

.....

   void OnGUI() {
        GUI.DrawTexture(new Rect(x, y, 32, 4), xGraphicsManager.Instance.LifeBarBackGround);
        GUI.DrawTexture(new Rect(x, y, 32 * CurHealth / Health, 4), xGraphicsManager.Instance.LifeBar);
        GUI.DrawTexture(new Rect(x + 8, y - 16, 16, 32), PlayerIcon);

    }

at first I figured out the viewports works with normalized values so I thought I could just multiply those values by the Camera width and height but the problem is, if something is, lets say for example (1.5, 0.5, 32) it is still draw on screen even if 1.5 is outside the viewport because 1.5*Camera width is still a valid pixel rect inside the screen… :face_with_spiral_eyes::face_with_spiral_eyes:

Ok, in case someone has the same problem as me this is what I did:

private Camera[] Cameras;
void Start () {
        Cameras = Camera.allCameras;
    }
void OnGUI() {
        foreach (Camera Cam in Cameras){
        Vector3 ViewPortPos = Cam.WorldToViewportPoint(PlayerCharacter.transform.position);
        if (ViewPortPos.x > 0.05f && ViewPortPos.x < 0.95f && ViewPortPos.y > 0.05f && ViewPortPos.y < 0.95f){
        Vector3 screenPos =  Cam.ViewportToScreenPoint(ViewPortPos);
        x = screenPos.x - xOffset; // x offset
        y = Screen.height - screenPos.y - yOffset; // y offset
        GUI.DrawTexture(new Rect(x, y, 32, 4), xGraphicsManager.Instance.LifeBarBackGround);
        GUI.DrawTexture(new Rect(x, y, 32 * CurHealth / Health, 4), xGraphicsManager.Instance.LifeBar);
        GUI.DrawTexture(new Rect(x + 8, y - 16, 16, 32), PlayerIcon);
            }
        }

    }