Tasharen Entertainment Forum

Support => NGUI 3 Support => Topic started by: noporcru on April 15, 2014, 05:53:53 PM

Title: How to use NGUI to implement a crosshair
Post by: noporcru on April 15, 2014, 05:53:53 PM
Would I just create a new Sprite widget? Currently I'm using Unity's OnGUI and I have this:

//if not paused
      if(Time.timeScale != 0)
      {
         if(crosshairTexture != null)
            GUI.DrawTexture(new Rect((Screen.width - crosshairTexture.width) / 2f,
                                     (Screen.height - crosshairTexture.height) /2f, crosshairTexture.width*crosshairScale, crosshairTexture.height*crosshairScale),crosshairTexture);

but I want to use NGUI. Thanks in advance.
Title: Re: How to use NGUI to implement a crosshair
Post by: ArenMook on April 16, 2014, 10:28:29 AM
Add a sprite, add a script to it that will make it follow the Input.mousePosition. You will want to convert screen coordinates to NGUI's virtual pixels if your UIRoot is not pixel-perfect. You can use this function:
  1.         static public Vector2 ScreenToParentPixels (Vector2 pos, Transform relativeTo)
  2.         {
  3.                 int layer = relativeTo.gameObject.layer;
  4.                 if (relativeTo.parent != null)
  5.                         relativeTo = relativeTo.parent;
  6.  
  7.                 Camera cam = NGUITools.FindCameraForLayer(layer);
  8.  
  9.                 if (cam == null)
  10.                 {
  11.                         Debug.LogWarning("No camera found for layer " + layer);
  12.                         return pos;
  13.                 }
  14.  
  15.                 Vector3 wp = cam.ScreenToWorldPoint(pos);
  16.                 return (relativeTo != null) ? relativeTo.InverseTransformPoint(wp) : wp;
  17.         }
You can then position your sprite using
  1. sprite.transform.localPosition = ScreenToParentPixels(Input.mousePosition, sprite.transform);
Title: Re: How to use NGUI to implement a crosshair
Post by: r.pedra on April 16, 2014, 10:37:08 AM
Why does the crosshair have to follow the mouse? If I remember right, a crosshair is not meant to move from the middle of the screen right?
Title: Re: How to use NGUI to implement a crosshair
Post by: ArenMook on April 16, 2014, 10:41:39 AM
It's just an example. You can make it follow whatever you like.