I’m mostly there already, but for some reason, the text appears on the camera screen while it is looking away from the player. Do I need to dot the camera vector, or is there some other way to hide the text if it is off the screen?
By the way, I’m using WorldToViewportPoint.
WorldToViewportPoint returns a viewport point even if you’re looking in the opposite direction. You can use some trick to disable the nametag when the camera isn’t looking in the object direction. If only one camera is being used, you can display the label only when the player’s renderer.isVisible is true. Supposing the label is a GUIText, and that the script has a target Transform variable to link the label to the player, you can do something like this:
function Update(){
if (target.renderer.isVisible){
// target in the camera frustum: calculate the label coordinates
guiText.enabled = true;
} else {
guiText.enabled = false;
}
}
Here is a snippet of code that I use to place a quick GUI label above something in the world.
// Start with world coordinates.
Vector3 pos = mHitAgent.transform.position;
pos.y += 2; // The height of the agent plus a little bit.
// Convert to screen coordinates.
// mCam is the main camera.
pos = mCam.WorldToScreenPoint(pos);
// The GUI uses a different y-axis. So another conversion
// is needed for the y-axis. (Flip it.)
// Also, add some offsets to center the text.
Rect rect = new Rect(pos.x - 10
, Screen.height - pos.y - 15
, 100
, 22);
GUI.Label(rect, mHitAgent.name);
The GUI label will draw only if the rectangle overlaps the viewable area of the screen.
If you aren't using GUI to draw the label, then you can compare the rectangle against the Screen information to manually determine if there is overlap.
Thanks guys… that answers my question perfectly.