- Home /
Best way to do touch in with Unity2D?
Browsing around I've seen a lot of different methods of doing touch in Unity. I'm making a 2D touch game and I obviously want to use the new 2D functions in Unity. So I was wondering what the best way to do touch is? I need to be able to tap, drag, hold and all that. Below are a few of the examples I've found in other threads and answers.
First one I found. Might not be suitable for 2D. Also can Anyone explain the pro and cons of using SendMessage as the original author did? Wouldn't it be better to do it like you would normally? I've never seen or used this method at least, but I'm still new so..
foreach (Touch touch in Input.touches) {
Ray ray = camera.ScreenPointToRay(touch.position);
if (Physics.Raycast(ray, out hit, touchInputMask)) {
GameObject recipient = hit.transform.gameObject;
touchList.Add(recipient);
if (touch.phase == TouchPhase.Began) {
recipient.SendMessage("onTouchDown", SendMessageOptions.DontRequireReceiver);
}
if (touch.phase == TouchPhase.Ended) {
recipient.SendMessage("onTouchUp", SendMessageOptions.DontRequireReceiver);
}
}
}
I also found this one which seems pretty simple:
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
Vector2 touchPos = new Vector2(wp.x, wp.y);
if (collider2D == Physics2D.OverlapPoint(touchPos)) {
//Code for touch
}
So please let me know what you think. What method should I use? Any of these two or something else? Thanks!
I would suggest that you use the First code sample. This is typically how touches are done using TouchPhase. You certainly do not have to use Send$$anonymous$$essage, it is just easier for you to call Send$$anonymous$$essage than it is to acquire the gameObject and then get it's script and then call the necessary function. They are roughly the same cost, Send$$anonymous$$essage may be a little slower though.