2
\$\begingroup\$

I am working on a 2D game, and my camera is a orthographic with a size of 320.

I want to display some text, but not with OnGUI(). Rather, with a GUI Text game object.

I couldn't help but notice that positioning my GUI Text object is a real pain: apparently, the onscreen coordinates where the text appears range from 0 to 1. That is, 0.5 is the center of the screen.

If I wanted to put my label at exactly (100,50) regardless of the screen size, I would have to calculate something like

(100f / Screen.width, 50f / Screen.height)

Is there a way to tell the GUI Text to appear at the actual transform position as it appears on the scene editor? Currently, if you move the GUI Text game object's transform slightly to the right, the rendered text will be displaced a LOT to the right instead...

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

Camera.WorldToViewportPoint() can be used to map from world to viewpoint coordinates.

For static content the following line could be added to an Awake() method.

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

For dynamic content I add the GUIText or GUITexture to a child gameObject. Then on this child I attach a script with code like this:

public Vector3 WorldOffset = Vector3.up * 2.0f;
public Vector3 ScreenOffset = Vector3.zero;
new private Transform transform;
new private Camera camera;
private Transform target;

public void Awake() {
    transform = GetComponent<Transform>();
    target = transform.parent;
    camera = Camera.main;
}

public void LateUpdate() {
    transform.position = camera.WorldToViewportPoint(target.position + WorldOffset) + ScreenOffset;
}

This allows the parent object to move around in world coordinates as required, while the GUI appears to follow despite moving in viewport coordinates.

\$\endgroup\$
-1
\$\begingroup\$
void OnGUI()
{
  float xScreen = 100f;
  float zScreen = 50f;
  GUI.Label(New Rect(Screen.width / 2 - xScreen / 2, Screen.height / 2 - zScreen / 2, xScreen, zScreen), "[&]");
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to the site xlmnxp. We expect answers to be more fleshed out and describe what they're doing. Here you've just posted code, which, while it may work, is only part of the answer. Further note that the question specifically asks not use use OnGUI. \$\endgroup\$
    – House
    Sep 30, 2014 at 5:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .