Hide GUIText when GameObject is behind Camera

How would you go about hiding the GUI text when the GameObject is behind the main Camera? Here’s an example.

The temp S button on the bottom right enables and disables the object names, the code is here.

	void Update () {
		
		if (showName == true) DisplayNameOn (true);
	}
	
	void DisplayNameOn (bool showName) { // Gets called on Broadcast or if HoverText is On.
		
		if (showName == false) {
			HoverTextfolder = GameObject.Find("HoverText");
			Info.showName = true;
			hoverText = GameObject.Instantiate(Resources.Load("Hover Text")) as GameObject;
			GUIText name = hoverText.GetComponent<GUIText>();
			name.text = Name;
			hoverText.transform.parent = HoverTextfolder.transform;
		}
		if (hoverText) hoverText.transform.position = Camera.main.WorldToViewportPoint(transform.position) + new Vector3(-0.006f, 0.03f, 0f); // Change the 0.05f value to some other value for desired height
	}
	
}

The Satellite named Callisto and Europa is behind me and shows up on my main Camera. Same as vice versa.

2 Answers

2

I haven’t tested this, but it should work perfectly.

Use the following code:

OnCameraMove () { // Wherever you handle your camera movement
    // Movement calculations
    GameObject[] satelites = GameObject.FindGameObjectsWithTag("WhateverYouCallYourSatelites");

    // every time you move your camera you can step through all the satellites to see if you should turn their names on or off
    foreach (GameObject go in satelites) {
        if (IsBehind(Camera.maincamera, go)) {
            go.GetComponent<NameOfScriptOnObjectThatHandlesTheNameDisplay>().TurnNameOff(); // Where the TurnNameOff() method is whatever method you use to turn the name on or off
        }
        else {
            go.GetComponent<NameOfScriptOnObjectThatHandlesTheNameDisplay>().TurnNameOn();
        }
    }
}
        
//Checks if targetOther is behind targetThis
bool IsBehind(gameObject targetThis, targetOther) {
    Vector3 toTarget = (targetOther.position - targetThis.position).normalized;
    return (Vector3.Dot(toTarget, transform.forward) > 0);
}

Refer to the following for more information:

Unity explanation of the dot product

Website I refer to constantly to refresh my maths

thx for your reply, take a look at my answer see if you find it simplified.

I found a quicker and shorter way.

if (hoverText){
   var planes = GeometryUtility.CalculateFrustumPlanes(Camera.main);
   if (GeometryUtility.TestPlanesAABB(planes, transform.collider.bounds)) hoverText.GetComponent<GUIText>().enabled = true;
   else hoverText.GetComponent<GUIText>().enabled = false;
}

So when the Satellite or Planet (which contains a collider) is in front of the camera, its enabled, if its not, then its disabled.