Author Topic: How to use NGUI to implement a crosshair  (Read 1816 times)

noporcru

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 6
    • View Profile
How to use NGUI to implement a crosshair
« 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.

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: How to use NGUI to implement a crosshair
« Reply #1 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);

r.pedra

  • Full Member
  • ***
  • Thank You
  • -Given: 7
  • -Receive: 20
  • Posts: 131
    • View Profile
Re: How to use NGUI to implement a crosshair
« Reply #2 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?

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: How to use NGUI to implement a crosshair
« Reply #3 on: April 16, 2014, 10:41:39 AM »
It's just an example. You can make it follow whatever you like.