tap detection on a gameobject in unity

Ophélia picture Ophélia · Jul 25, 2016 · Viewed 48.6k times · Source

i'm currently making a soccer game.

In this mini-game, when the player touch the ball, it adds force, and the goal is to make the higher score.

So i wrote:

 void Update()
{
    if(Input.touchCount == 1 && Input.GetTouch(0).phase== TouchPhase.Began)
      {
       AddForce, and playsound ect...
      }

}

With this, when i touch anywhere on the screen, it adds force, but i just want to add force when i touch my gameobject (the ball).

How can i do that?

Thanks! :)

Answer

Programmer picture Programmer · Jul 25, 2016

With this, when i touch anywhere on the screen, it adds force, but i just want to add force when i touch my gameobject (the ball).

To detect tap on a particular GameObject, you have to use Raycast to detect click on that soccer ball. Just make sure that a collider(eg Sphere Collider) is attached to it.

void Update()
{
    if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
    {
        Ray raycast = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
        RaycastHit raycastHit;
        if (Physics.Raycast(raycast, out raycastHit))
        {
            Debug.Log("Something Hit");
            if (raycastHit.collider.name == "Soccer")
            {
                Debug.Log("Soccer Ball clicked");
            }

            //OR with Tag

            if (raycastHit.collider.CompareTag("SoccerTag"))
            {
                Debug.Log("Soccer Ball clicked");
            }
        }
    }
}