Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect touch on a game object

I'm developing a game on Unity for iOS devices. I've implemented the following code for touch:

void Update () {
    ApplyForce ();
}

void ApplyForce() {

    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
        Debug.Log("Touch Occured");     
    }
}

I've dragged this script onto my game object which is a sphere. But the log message appears no matter where I touch. I want to detect touch only when the users touches the object.

like image 229
Ashish Beuwria Avatar asked Dec 01 '22 02:12

Ashish Beuwria


2 Answers

stick the code bellow in your camera, or something else that will persist in the level you're designing. It can be anything, even an empty gameobject. The only important thing is that it only exists ONCE in your level, otherwise you'll have multiple touch checks running at the same time, which will cause some seriously heavy load on the system.

void Update () {
    if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) 
    {
        Ray ray = Camera.main.ScreenPointToRay( Input.GetTouch(0).position );
        RaycastHit hit;

        if ( Physics.Raycast(ray, out hit) && hit.transform.gameObject.Name == "myGameObjectName")
        {
            hit.GetComponent<TouchObjectScript>().ApplyForce();  
        }
    }
}

In the above script, hit.transform.gameObject.Name == "myGameObjectName" can be replaced by any other method you want to check that the object hit by the raycast is the object you want to apply a force to. One easy method is by Tags for example.

Another thing to keep in mind is that raycast will originate at your camera (at the position relative to your finger's touch) and hit the first object with a collider. So if your object is hidden behind something else, you won't be able to touch it.

Also put the script bellow in your touch object (in this example, called TouchObjectScript.cs)

void Update () {
}

public void ApplyForce() {

        Debug.Log("Touch Occured");   
}

If something wasn't clear, or you need any further help, leave a comment and I'll get back to you.

like image 111
Steven Mills Avatar answered Dec 04 '22 20:12

Steven Mills


The best way to do this, is just adding:

void OnMouseDown () {}

to the gameobject you want to be clicked. The problem with this is that you cannot press 2 things at one time.

like image 40
Wiebren de Haan Avatar answered Dec 04 '22 21:12

Wiebren de Haan