- Home /
Get clicked object cords on object ? Unity2D
Hello folks! I'm doing some tests with clicking object and what do get clicked object cords on object.
I think image show exactly what i want to achieve. Here is my click call block:
checkPosition (Input.GetTouch (0).position);
And here is function that is called from this block.
private void checkPosition(Vector2 vec){
Vector3 wp = Camera.main.ScreenToWorldPoint (vec);
Vector2 touchPos = new Vector2 (wp.x, wp.y);
var hit = Physics2D.OverlapPoint (touchPos);
if (hit) {
Debug.Log(hit.transform.gameObject.name);
Debug.Log(hit.transform.position.x + " | " + hit.transform.position.y);
hit.transform.gameObject.SendMessage("Touched",0,SendMessageOptions.DontRequireReceiver);
}
}
Any advice will be great how to get thous cords.
Answer by robertbu · Oct 11, 2014 at 03:31 PM
The solution will vary depending on the type of object. The easiest would be a Quad.
Convert the point to a local coordinate using Transform.InverseTransformPoint()
Add (0.5, 0.5, 0.0) to the result. This is because coordinates are relative to the pivot, and the pivot is in the center. By adding this vector, you are placing the origin in the lower left corner.
Multiply the result by the Transform.localScale
private void checkPosition(Vector2 vec){
Vector3 wp = Camera.main.ScreenToWorldPoint (vec);
Vector2 touchPos = new Vector2 (wp.x, wp.y);
var hit = Physics2D.OverlapPoint (touchPos);
if (hit) {
Vector3 tempVect = transform.InverseTransformPoint(hit.transform.gameObject.transform.position);
Vector2 tempv2 = new Vector2(tempVect.x,tempVect.y);
tempv2 = tempv2 + new Vector2(0.5f,0.5f);
tempv2 = new Vector2(tempv2.x * hit.transform.gameObject.transform.localScale.x,tempv2.y*hit.transform.gameObject.transform.localScale.y);
Debug.Log(tempVect.x+" | "+ tempVect.y);
}
}
Tryed this but still gets same cords even if i click other side of object .
Here is a rewrite of your code that will work with a Quad.
using UnityEngine;
using System.Collections;
public class Example: $$anonymous$$onoBehaviour {
void Update () {
if (Input.Get$$anonymous$$ouseButtonDown (0)) {
CheckPosition(Input.mousePosition);
}
}
private void CheckPosition(Vector3 vec){
vec = Camera.main.ScreenToWorldPoint (vec);
Collider2D col = Physics2D.OverlapPoint (vec);
if (col != null) {
Vector3 v = col.transform.InverseTransformPoint(vec);
v += new Vector3(0.5f,0.5f, 0.0f);
v = Vector3.Scale (v, col.transform.localScale);
Debug.Log(v.x+" | "+ v.y);
}
}
}
For code like this to work, it is necessary to know the real world size of the object. A Quad is a know size (1 x 1), which makes the calculations easy.