Get local position of pointer on scaled texture (2D)
I have a GameObject with a SpriteRendere. On startup (in Start()) a 1024x768 pixels Texture2D will be created and attached as the sprite in the SpriteRendere. The pivot of my texture is to (0.5, 0.5) så it scales around the centre of the screen.
While the scale of the GameObject is (1.0, 1.0) I have no problem on detecting the mouseposition on the texture as it's size is equivalent to the size of the screen. However, when I scale the GameObject, and thereby the texture, I can't figure out how to get the position locally in the GameObject.
Q: How do I translate the mouse position in the screen space to the x-y-coords of the GameObject when it is scaled to stretch beyond the screen and you therefore only see a portion of the GameObject?
Answer by mollermanden · Jan 20, 2016 at 07:50 AM
I happend to solve this myself using the Transform.inverseTransform()
method.
As I am using the EventSystem I use the eventData.position to get the pointer position and then the below line of code translates the pointerposition to local coordinates on my texture which seems to work no matter where the texture is positioned or how it's scaled. Note that the position is translated to world coords before it's translated to local coords.
Vector3 localPosition = transform.InverseTransformPoint(Camera.main.ScreenToWorldPoint(pointerPosition));
A more complete example:
public void OnPointerDown(UnityEngine.EventSystems.PointerEventData eventData) {
this.logPosition(eventData.position);
}
private void drawPixel(Vector2 pointerPosition) {
Vector3 localPosition = transform.InverseTransformPoint(Camera.main.ScreenToWorldPoint(pointerPosition));
Debug.Log(localPosition);
}
Your answer
Follow this Question
Related Questions
[SOLVED] Problems creating a Sprite through script 0 Answers
how do i make my character float down? 0 Answers
Shader Graph: How do I rotate a texture that is part of a larger texture? 0 Answers
Noob question about 2D graphic drawing system 0 Answers
Which version of Unity is more suitable for a pure 2D mobile game for a newbie? 0 Answers