- Home /
How can I change touch location to map location?
I am trying to locate a cube object at the position where I touched with this code. However, the only result I can see is "Touched". I think ScreenToWorldPoint is not working. Did I made a mistake in this code?
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.touchCount > 0)
{
UnityEngine.Debug.Log("Touched");
Vector2 pos_2 = Input.GetTouch(0).position;
Camera camera = GetComponent<Camera>();
Vector3 pos_3 = camera.ScreenToWorldPoint(pos_2);
UnityEngine.Debug.Log("pos_3: "+pos_3);
//Vector3 pos_3 = new Vector3(pos_2.x, pos_2.y, 0);
transform.position = pos_3;
}
}
}
I also have the same problem when I change 'if' to this. if (Input.Get$$anonymous$$ouseButtonDown(0)) { UnityEngine.Debug.Log("Touched"); this.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition); }
It seems you're trying to do a GetComponent() on the same object as the cube. That's probably returning a null ref and the code doesn't move forward. You can always call the camera like this:
Vector3 pos_3 = Camera.main.ScreenToWorldPoint(pos_2);
oh thanks for the help! but i tried as you said but it's still not working....
// Update is called once per frame void Update () { if (Input.touchCount > 0) { UnityEngine.Debug.Log("Touched"); Vector2 pos_2 = Input.GetTouch(0).position; Vector3 pos_3 = Camera.main.ScreenToWorldPoint(pos_2); UnityEngine.Debug.Log("pos_3: "+pos_3); transform.position = pos_3; } }
Answer by sujitmarcus · Jan 22, 2019 at 11:58 AM
You are current asking for Touch on screen but if you need to Output "Touch" from touching a specific object on screen you have to learn about Raycasting. Here you can try.
if (Input.touchCount == 1 && Input.GetTouch(0).phase == touchPhase) {
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit hit;
Debug.DrawRay(ray.origin, ray.direction * 100, Color.yellow, 100f);
if(Physics.Raycast(ray, out hit))
{
Debug.Log(hit.transform.name);
if (hit.collider.tag == "Cube" ) {
Debug.Log("Touched" + hit.transform.name);
}
}
}
Note: Don't Forget to assign "Cube" tag to your object in order to this code to work.