- Home /
Worldspace Conversion
I'd like to place a Label above a GameObject. To do this, it seems I need to convert the GameObjects worldspace coordinates to screenspace. Anyone have an example of doing this? Thanks!
I'm thinking it goes something like this...
Vector3 sp = camera.WorldToScreenPoint(transform.position);
???
Rect r = new Rect(???);
GUI.Label(r, "Hello World!");
Answer by The_r0nin · Dec 14, 2010 at 09:02 PM
In javascript:
var mainCam: Camera = Camera.main; //I always cache component variables used frequently.
OnGUI(){
screenLoc: Vector3 = mainCam.WorldToScreenPoint(transform.position); GUI.Label (Rect(screenLoc.x-25,screenLoc.y-20,50,20),"My Tag");
That should give you a label 20 pixels above your object center and centered over it (50 pixels wide). If you want the label to be above the top of the object, use renderer.bounds (and then min/max or extends). A script that labels objects (for you to look at) in the wiki is HERE.
It only seems to work when the GameObject is close to the center of the screen, As it gets near the top and bottom, the space between the text and object gets larger. This is a 2D,setup with the camera along the z-axis. Thanks!
That script you pointed me too is very helpful, thanks!
Just a heads up to others, WorldToScreenPoint() gives a y position in relation to the bottom of the screen being 0, whereas GUI has 0 at the top of the screen. So if your camera is not stationary (e.g. player jumps), the label over the game object will rise. To fix this use this for the y parameter of the Rect:
Screen.height - screenLoc.y - 20