I wrote this rough script to place a ui element which is a box at the position of the target it works fine but when i get past the target and its not in the view it still projects the ui element on the screen any way to fix this or a better solution to this?
public class rdrtst : MonoBehaviour
{
public RectTransform targetUi;
public GameObject target;
Vector3 targetVectorPosition;
// Update is called once per frame
void Update()
{
targetVectorPosition = target.transform.position;
targetVectorPosition = Camera.main.WorldToScreenPoint(targetVectorPosition);
targetUi.transform.position = targetVectorPosition;
}
}
In view

Not in view(should not be visible)

1 Like
Make a Debug.Log and let it print the screen position. If z component is negative (not sure) when object is behind camera you could check for that.
If that does not work check this .
1 Like
Thanks the calculating based on z component was buggy but the with angle calculation it works pretty well
public class rdrtst : MonoBehaviour
{
public RectTransform targetUi;
public GameObject target;
public GameObject Player;
Vector3 targetVectorPosition;
// Update is called once per frame
void Update()
{
Vector3 targetVector = target.transform.position - Player.transform.position;
Vector3 playerForward = Player.transform.forward;
float angle = Vector3.Angle(playerForward, targetVector);
if(angle<45)
{
targetVectorPosition = target.transform.position;
targetVectorPosition = Camera.main.WorldToScreenPoint(targetVectorPosition);
targetUi.GetComponent<Image>().enabled = true;
targetUi.position = targetVectorPosition;
}
else
{
targetUi.GetComponent<Image>().enabled = false;
}
}
}
1 Like