Author Topic: Mouse Coordinates Relative To Widget  (Read 4823 times)

pfranza

  • Guest
Mouse Coordinates Relative To Widget
« on: May 20, 2013, 09:42:36 AM »
Sorry if this has been asked/answered in the past I did some searching and I could not find it.

I am trying to make a class that extends UITexture and add some mouse processing to it, but I need to be able to find the position of the mouse event relative to the widget.  I.e the upper left of the widget is (0,0) and the lower right of the widget is (transform.localScale.x, transform.localScale.y).

Can you point me in the right direction please?

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Mouse Coordinates Relative To Widget
« Reply #1 on: May 20, 2013, 09:54:34 AM »
  1. Vector2 screenPos = Input.mousePosition;
  2. Camera cam = NGUITools.FindCameraForLayer(gameObject.layer);
  3. Vector3 worldPos = cam.ScreenToWorldPoint(screenPos);
  4. Vector3 localPos = transform.worldToLocalMatrix.MultiplyPoint3x4(worldPos);
This gives you the local coordinates relative to the widget's pivot point. At this point if the pivot point is top-left, then you're done.

pfranza

  • Guest
Re: Mouse Coordinates Relative To Widget
« Reply #2 on: May 20, 2013, 01:05:02 PM »
So basically that gave me the positional bounds.   Then I converted that into a scaled pixel based on the localScale of the widget

  1. Vector2 screenPos = Input.mousePosition;
  2. Camera cam = NGUITools.FindCameraForLayer(gameObject.layer);
  3. Vector3 worldPos = cam.ScreenToWorldPoint(screenPos);
  4. Vector3 localPos = transform.worldToLocalMatrix.MultiplyPoint3x4(worldPos);
  5. Bounds b = NGUIMath.CalculateRelativeWidgetBounds(transform, cam.transform);
  6.        
  7. float mx = ((float)(localPos.x + b.extents.x))/ (2.0F * b.extents.x) * transform.localScale.x;
  8. float my = ((float)((localPos.y * -1F) + b.extents.y))/ (2.0F * b.extents.y) * transform.localScale.y;
  9. return new UnityEngine.Vector2(mx, my);
  10.  
  11.  

This places the coord (0,0) in the upper left and (transform.localScale.x, transform.localScale.y) in the lower right.  This seems to work, just in case anybody else needs such a thing.

Thanks for your help