x


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!");
more ▼

asked Dec 14 '10 at 08:39 PM

spaceshooter gravatar image

spaceshooter
249 49 55 69

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered Dec 14 '10 at 09:02 PM

The_r0nin gravatar image

The_r0nin
1.4k 9 14 30

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!

Dec 14 '10 at 09:18 PM spaceshooter

That script you pointed me too is very helpful, thanks!

Dec 14 '10 at 11:51 PM spaceshooter

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

Jul 30 '12 at 06:10 PM weezma2004
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x32
x25
x16

asked: Dec 14 '10 at 08:39 PM

Seen: 2185 times

Last Updated: Jul 30 '12 at 06:10 PM