Author Topic: set the coordinates of UISprite from Input.mousePosition  (Read 3917 times)

tananuka

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 2
    • View Profile
set the coordinates of UISprite from Input.mousePosition
« on: August 20, 2014, 07:08:51 AM »
How to put a new sprite to the point where the mouse was clicked?
Here's how it should look:
  1.  
  2. Vector3 posSprite = new Vector3();
  3. posSprite.x = Input.mousePosition.x - (float)Screen.width / 2;
  4. posSprite.y = Input.mousePosition.y - (float)Screen.height / 2;
  5.  
  6. GameObject go = NGUITools.AddChild( spriteParent, prefabMySprite);
  7. MyScriptControlUISprite script = go.GetComponent<MyScriptControlUISprite>();
  8. script.Setup(posSprite);
  9.  
  10.  
I need to first get the coordinates for the sprite
and then I have them initialize event "Start"
  1. public class MyScriptControlUISprite : MonoBehaviour {
  2. private Vector3  _startPosition;
  3.        public void Setup(Vector3  startPosition)
  4.        {
  5.               _startPosition = startPosition;
  6.        }
  7.        void Start()
  8.        {
  9.               gameObject.GetComponent<UISprite>().transform.localPosition = _startPosition;
  10.        }
  11. }
  12.  
In this example, it works correctly only for the resolution of 16: 9
« Last Edit: August 20, 2014, 10:39:20 AM by tananuka »

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: set the coordinates of UISprite from Input.mousePosition
« Reply #1 on: August 20, 2014, 04:25:28 PM »
  1. Vector3 screenPos = UICamera.lastTouchPosition;
  2. Camera cam = NGUITools.FindCameraForLayer(gameObject.layer);
  3. Vector3 worldPos = cam.ScreenToWorldPoint(screenPos);
  4. Vector3 localPos = sprite.transform.parent.WorldToLocalPoint(worldPos);
  5. localPos.z = 0f;
  6. sprite.transform.localPosition = localPos;

P.S. You may also want to look at NGUIMath.WorldToLocalPoint, since it does most of this math inside. NGUIMath.OverlayPosition is also useful.

tananuka

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 2
    • View Profile
Re: set the coordinates of UISprite from Input.mousePosition
« Reply #2 on: August 21, 2014, 02:02:15 AM »
  1. Vector3 localPos = sprite.transform.parent.WorldToLocalPoint(worldPos);
-unacceptable!  ;)
  1. Vector3 localPos = sprite.transform.parent.worldToLocalMatrix.MultiplyPoint3x4(worldPos);
- replace!
And now it is Work!
ArenMook, Big Thanks!
« Last Edit: August 21, 2014, 02:11:39 AM by tananuka »