UI Image Follow GameObject

Hey!
Im trying to make an FPS shooter game were the player can scan the area and find different types of object (No man’s sky style). And I have this script attached to the UI Image (Icon) that is a child of my canvas.

Now the UI Image is following the GameObject perfectly. But whenever I turn away 180 degrees from the GameObject, It seems like the UI Image is located at the opposite side too (Or moves to the opposite side).

Any help? :slight_smile:
Thanks!

Heres the code:

public class TrackObject : MonoBehaviour {

    public GameObject Obj;

    Camera mCamera;
    private RectTransform rt;
    Vector2 pos;

    void Start ()
    {
        mCamera = GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<Camera> ();
        rt = GetComponent<RectTransform> ();
    }

    void Update ()
    {
        if (Obj)
        {
            pos = RectTransformUtility.WorldToScreenPoint (mCamera, Obj.transform.position);
            rt.position = pos;
        }
        else
        {
            Debug.LogError (this.gameObject.name + ": No Object Attached (TrackObject)");
        }
         
 
    }
}

1 Like

I know it is old but this can help someone

void OnGUI() {   
        var gotransform = Obj.GetComponent<Transform>();
        rt.position = mCamera.WorldToScreenPoint(gotransform.position);
      }
3 Likes

Not working.The image still moves over the opposite side

https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html
You can use the Z component of the position you are getting from WorldToScreenPoint in order to determin if the object is infront of behind the camera.
If the z value is positive is infront of the camera and if its negative you know its behind the camera.
I personally use a canvas group to and set the alpha to 1 or 0 depending if the object is infront or behind the camera.

1 Like

Many thanks. Your idea helped))

If anyone’s still interested, here’s a version of the code that works even if the object is behind the camera:

        Vector3 targPos = Obj.transform.position;
        Vector3 camForward = mCamera.transform.forward;
        Vector3 camPos = mCamera.transform.position + camForward;
        float distInFrontOfCamera = Vector3.Dot(targPos - camPos, camForward);
        if (distInFrontOfCamera < 0f)
        {
            targPos -= camForward * distInFrontOfCamera;
        }
       pos = RectTransformUtility.WorldToScreenPoint (mCamera, targPos);

You can also clamp the resulting ‘pos’ to a rectangle within the screen, if you want the icon/text/whatever to hug the edge for offscreen objects.

6 Likes

Thank You Peeling! You are a life saver.