Touches in Unity

Posted on

in

,

In this example, there is a left and right button that moves the character in that direction. Both buttons have a box collider.

leftBox = GameObject.Find ("leftButton").GetComponent<BoxCollider2D> ();
rightBox = GameObject.Find ("rightButton").GetComponent<BoxCollider2D> ();

void Update () {
foreach (var touch in Input.touches) {
            if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled) {
                Vector2 wp = Camera.main.ScreenToWorldPoint (touch.position);
                Vector2 touchPos = new Vector2 (wp.xwp.y);
    
                    if (leftBox == Physics2D.OverlapPoint (touchPos)) {
                        //do stuff
                    }
                    if (rightBox == Physics2D.OverlapPoint (touchPos)) {
                        //do stuff
                }
            }
        }
}

Basically, we check each touch, convert it to world space and then check if the touch point is over the box collider area.

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930