How can I get the touch position on a specific 2D gameObject/sprite?
Searching these forums I’ve managed to record when I get a touch on an object using either a rayCast or the OnMouseDown method, but I want to retrieve the position on the object that was touched.
I’ve got these methods in a script attached to the gameObject in question and there will be not other gameObjects that I’m worried about clicking.
e.g
If I have a circle and I touch the left hand side of it, I want to move it right. If I touched it on the right hand side I want to move it left. I know how to apply force when it is touched, but I can’t work out what coordinates I clicked my object
(left and right were simple examples, in reality I would move it in any direction (e.g diagonals as well)
I actually managed to do this using the code below.
To be clear the issue I Was having was getting the clickPos in relation to the gameObject. I’d worked out how to add the force. Unfortunately I couldn’t answer my own question until it was approved!
In case anyone else needs it, this is the code i used to get the click position relative to the gameObject
if (Input.GetMouseButton (0)) {
Vector3 clickedPosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (clickedPosition, -Vector2.up);
if (hit) {
Vector3 hitPoint = this.transform.InverseTransformPoint (hit.point);
}
}