Unity touch detection on objects
I am trying to detect touch on objects by using rays. I dont get use of rays. I have two different projects that I try to learn touch inputs. One of them works fine identifies which objects being touchhed:
void Update()
{
if (Input.touchCount > 0)
{
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 != null)
{
GameObject touchedObject = hit.transform.gameObject;
Debug.Log("Touched " + touchedObject.transform.name);
}
}
and I have more complete project with several game objects in the scene. In this projects my code doesnt work at all and I dont get the difference, usage of rays:
void Update()
{
if (Input.touchCount > 0 && !correctPosition)
{
Touch touch = Input.GetTouch(0);
Vector3 touchPos = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 11f));
touchPos.z = gameObject.transform.position.z;
//transform.position = touchPos;
Ray raycast = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
RaycastHit raycastHit;
switch (touch.phase)
{
case TouchPhase.Began:
if (Physics.Raycast(raycast, out raycastHit))
{
if (raycastHit.collider != null)
{
Debug.Log(this.name);
}
}
break;
.
.
.
.
Comment