WorldToScreenPoint when object is behind the camera

Hi,

I am making a simple target indicator which shows and indicator on a gameobject (aircraft) when on screen and another when the object is offscreen. However, the solution i have now clamps the indicator to the screen but when the camera is facing away from the gameobject the indicator appears on the same point as when facing the gameobject. i guess this is because i am using world coordinates to determine the position of the airplane gameobject? Is it possible to have the offscreen indicator stick to the right position of the edge of the screen relative to the gameobject no matter which direction the camera is facing?

void Start () {
        targets = GameObject.FindGameObjectsWithTag("Enemy");
    }

    void OnGUI()
    {
        for (int i = 0; i < targets.Length; i++)
        {
            GameObject target = targets[i];
            Texture2D indicator;

            Vector3 screenPoint = Camera.main.WorldToScreenPoint(target.transform.position);

            if (screenPoint.z > 0 &&
               screenPoint.x > 0 && screenPoint.x < Screen.width &&
               screenPoint.y > 0 && screenPoint.y < Screen.height) {
                indicator = box;
            }
            else {
                indicator = arrow;
            }

            float halfScale = indicator.width / 2;
           
            Vector3 clampedPoint = new Vector3(
                Mathf.Clamp(screenPoint.x, halfScale, Screen.width - halfScale),
                Mathf.Clamp(screenPoint.y, halfScale, Screen.height - halfScale), screenPoint.z);

            Rect rect = new Rect(clampedPoint.x - halfScale,
                                 Screen.height - clampedPoint.y - halfScale,
                                 indicator.width,
                                 indicator.height);
           
            GUI.DrawTexture(rect, indicator, ScaleMode.ScaleToFit);
        }
    }

Thanks!

@h0nka Have you solved the problem?

Well, the issue is the way the projection works. You don’t just have a cone into the positive z direction, but also a cone into the negative direction. As for visually rendering things to the screen, anything behind the camera wouldn’t be rendered at all. What you can try is simply expanding the projected point into the distance if the projected z value is negative. Something like that:

if (screenPoint.z > 0 &&
    screenPoint.x > 0 && screenPoint.x < Screen.width &&
    screenPoint.y > 0 && screenPoint.y < Screen.height) {
        indicator = box;
    }
    else
    {
        indicator = arrow;
        if (screenPoint.z < 0f)
        {
            screenPoint *= 10000f;
        }
    }

Of course this only works with the clamping code that follows and may not result in the position you’re looking for. Note that when the object is exactly behind you, you still have some issues…