- Home /
world to screen coordinates conversion
Im trying to draw a crosshair texture where a gun in my ame is pointing. I use an Empty that is the child of the gun so it follows its movements. I than convert the coordinates of the Empty with the WorldToScreenPoint function and use GUI.DrawTexture to draw the crosshair at the right place.
However the vertical movement of the crosshair texture is inverted. When I point the gun up to the sky the crosshair moves to the bottom half of the screen and vice versa.
I tried unparenting the target Empty and still experienced the same results. Please tell me if I'm making some mistake here!
This is my script added to my Camera:
var crosshair : Transform; var crosshairTex : Texture2D; private var texPosition : Rect; private var pos : Vector3;
function OnGUI () { pos = camera.WorldToScreenPoint (crosshair.position); texPosition = Rect (pos.x - (crosshairTex.width / 2), pos.y - (crosshairTex.height / 2), crosshairTex.width, crosshairTex.height);
GUI.DrawTexture (texPosition, crosshairTex);
}
Answer by Eric5h5 · Oct 30, 2010 at 07:36 PM
OnGUI doesn't use screen coords; it uses GUI coords which are top-down and not bottom-up. It would be a little faster to use a GUITexture gameobject instead, in combination with WorldToViewportPoint, but if you need to use OnGUI, you can invert the Y coord by subtracting it from Screen.height.
I think GUITexture uses fractions. So the centre of the screen is (0.50, 0.50). So I would heve to use soemthin like (pos.x / Screen.width) to define the position.
@LeiterJakab: No, you'd use WorldToViewportPoint, as I mentioned.
Got carried away with my plan when I started writing the script. Both of your solutions work fine, thank you for the quick answers.