Onscreen objective pointer

I would like to create a gui texture which “points”(i.e. is placed at) a physical 3d object. I read alot about this line of code:

Camera.mainCamera.WorldToScreenPoint(target.transform.position);

But when I implement it, it gives me strange values. At some stages it gives me something like 7500 for my x. The tiny game screen in the centre only displays a range of 0->0.9 for x and y, so any value above 1 is not renderable.

How can I implement WorldToScreenPoint correctly?

#pragma strict

public var objectiveIcon : GUITexture;
public var objectiveDescription : GUIText;
private var icon : GUITexture;
private var description : GUIText;

function Start ()
{
	icon = Instantiate(objectiveIcon);
	description = Instantiate(objectiveDescription);
}

function Update ()
{
	icon.transform.position = Camera.mainCamera.WorldToScreenPoint (this.transform.position);
	icon.transform.position.y = Screen.height - icon.transform.position.y;
	description.transform.position = Camera.mainCamera.WorldToScreenPoint (this.transform.position);
	description.transform.position.y = Screen.height - icon.transform.position.y;
	Debug.Log(icon.transform.position.ToString());
	Debug.Log(description.transform.position.ToString());
}

function OnDestroy ()
{
	Destroy(icon);
	Destroy(description);
}

1 Answer

1

WorldToScreenPoint() returns the positions in screen pixels. But a GUITexture lives in Viewport space. Viewport space starts at 0,0 in the bottom left corner and goes to 1,1 in the upper right. So to place a GUITexture you want to use Camera.WorldToViewportPoint().

transform.position = Camera.main.WorldToViewportPoint(target.transform.position);

Also with this logic, you don’t want to be adjusting the ‘y’ height of the position using screen coordinates as you do on line 19. You can adjust where to anchor the image using the PixelInset rect associated with the GUITexture. In the particular case of your logic above, you will want to set your anchor point to the middle top of the texture and then you will set your ‘y’ position to 1.0.

Thank you very much! Uh, sorry about that Y thing. I did it only because everybody wrote that onscreen Y works inversely with WorldToScrenPoint.

–

There is a difference between a GUITexture and GUI.DrawTexture. The latter is from the GUI interface and lives in GUI coordinates. GUI coordiantes are screen coordinates that start in the upper left corner rather than the lower left corner. So if you were trying to place a GUI.DrawTexture at a world position you would first convert to screen coordinates and then you would have to do make the conversion that 'everybody wrote' about.

–

Any chance you have two camera viewing the scene?

–

I have a top-view minimap camera. Its settings exclude the layer that the scripted object is in. Any way I can debug / fix? @Edit the second camera doesn't have a guiLayer either. When I disable the guiLayer on Main Camera both guiTextures disappear.

–