Support => NGUI 3 Support => Topic started by: ScottV42 on May 07, 2014, 08:12:37 PM
Title: Trouble moving a Sprite to where the user clicked.
Post by: ScottV42 on May 07, 2014, 08:12:37 PM
I have an existing menu that I want to move where the user clicked. I have search the forums, and found some articles, but I can't seem to make any sense out of them.
Here is the code that is triggered when the user clicks. The TerrainConditionDropDown is a GameObject with the UISprite script.
public GameObject TerrainConditionDropDown; Vector3 worldClickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); TerrainConditionDropDown.transform.localPosition = TerrainConditionDropDown.transform.parent.InverseTransformPoint(worldClickPos);
By manually moving the TerrainConditionDropDown to a desired spot, the transform displayed in the inspector is (184,357,-4). When I click on the same desired spot, the above code is triggered, and the transform becomes (-4684, 674, -10799).
Multiple forum posts lead to this code fixing the problem, but I don't know what type of object widget represents. widget.transform.localPosition = widget.transform.parent.InverseTransformPoint(worldPos);
Thanks
Title: Re: Trouble moving a Sprite to where the user clicked.
Post by: ArenMook on May 08, 2014, 02:49:47 AM
'widget' is your UIWidget. Whatever you're trying to position in your UI hierarchy. This would be your menu object if you have that instead, assuming your menu is a part of your hierarchy like so:
UIRoot - UI Camera - Menu <- this one -- Widget 1 -- Widget 2 -- Widget 3
Title: Re: Trouble moving a Sprite to where the user clicked.
Post by: ScottV42 on May 08, 2014, 10:17:46 AM
Thank you for that clarification.
In the code below, the TerrainConditionDropDown is set to a UIWidget that is a direct child of UIRoot. As far as I can tell, this matches your example.
The InverseTransformPoint is returning a position very far away from the desired point, and I don't understand why. The desired position is (184,357,-4) and the position returned by InverseTransformPoint is (-4684, 674, -10799).
Title: Re: Trouble moving a Sprite to where the user clicked.
Post by: ArenMook on May 09, 2014, 05:23:25 AM
Is there depth involved? (is your Camera.main 3D?) Because mouse position only has 2D coordinates, and you'd need the actual 3D point, so a Raycast would be required.
If you are doing it from any NGUI event, such as OnClick, try this instead: