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?
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)");
}
}
}
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.