- Home /
How to detect Tap on object
Here is my code. PROBLEM IS IN COMMENTS IN CODE
void Update () {
int i = 0;
while (i < Input.touchCount) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Debug.Log("TAP !");
// TILL HERE IT WORKS
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
// BUT IT DOES NOT PRINT OUT HIT AND MORE
Debug.Log("HIT !");
if(hit.transform.name=="Bomb")
{
Debug.Log("HIT BOMB!");
}
}
}
++i;
}
}
Your line with the Ray should be:
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
oh no sorry that is a typo.my original script had Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
it still does not work
Yes it has a circle collider 2D. I have a script which randomly creates the object. I have no objects in scene initially.
Answer by HarshadK · Dec 29, 2014 at 12:01 PM
Based off this comment of yours:
Yes it has a circle collider 2D. I have a script which randomly creates the object. I have no objects in scene initially.
You need to use Physics2D.Raycast since it is a 2D game.
Oh ok I took a look at Physics2D.Raycast and trying to come up with code that works. Will get back here if I get any more problems and to post the working code
Thanks for pointing me to the right direction. Here is the working code void Update () {
int i = 0;
while (i < Input.touchCount) {
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
//Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position), -Vector2.up);
Debug.Log("TAP !");
if (hit.collider != null) {
if(hit.collider.tag=="Bomb")
{
Debug.Log("HIT BO$$anonymous$$B! ");
}
}
}
++i;
}
}