Tasharen Entertainment Forum

Support => NGUI 3 Support => Topic started by: papatriz on January 14, 2016, 01:06:14 PM

Title: Convert screen position to local coords problem.
Post by: papatriz on January 14, 2016, 01:06:14 PM
Hello, mates.

I try to make a very simple thing using NGUI - instantiate a label at the position of cursor after click.

Previously I did it using Unity UI without any problem, but now I have to switch to NGUI (due to very bad performance of native Unity scrollview).

So I found a few solution, included one from ArenMook:

  1. 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 = Camera;
  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.         }

I use it in this way:

  1. public void OnMouseDown()
  2.         {
  3.  
  4.                 Vector2 mouseScreenPosition = Input.mousePosition;
  5.  
  6.                 GameObject floatText = NGUITools.AddChild (CanvasParent, FloatTextPrefab); // CanvasParent = UIRoot
  7.  
  8.                 floatText.transform.position = ScreenToParentPixels(mouseScreenPosition, floatText.transform.parent) / 360; // magic number to scale according UIRoot scale;
  9.  
  10.                 floatText.GetComponentInChildren<UILabel>().text = someText;
  11.  
  12.         }

But unfortunately it doesn't work as expected.

First, result does not count scale of UIRoot - so coords much bigger. You can see a "magic" number in my code (360) - it's for rescaling back.

But main problem is that coords are not correct. It works ok near the screen center, but the greater the distance from center, the greater the difference.

Anybody can help me with it please? Maybe I miss something or so on..

I also made a lot of tests with different UIRoot scaling styles and other solutions like using transform.worldToLocalMatrix.MultiplyPoint3x4(worldPos).. To be honest,  this issue ruined my day  ;D



Title: Re: Convert screen position to local coords problem.
Post by: ArenMook on January 16, 2016, 01:31:56 PM
ScreenToParentPixels gives you local position, but you are trying to set world position.

Change "floatText.transform.position" to "floatText.transform.localPosition".
Title: Re: Convert screen position to local coords problem.
Post by: papatriz on January 17, 2016, 07:16:16 AM
Thanks! It works now.