- Home /
This code only works on 3D Colliders and I want it to work on 2D. What do I need to change?
using UnityEngine; using System.Collections;
public class TouchInput : MonoBehaviour {
public LayerMask touchInputMask;
private RaycastHit hit;
// Update is called once per frame
void Update () {
if(Input.touchCount > 0){
foreach (Touch touch in Input.touches){
Ray ray = camera.ScreenPointToRay(touch.position);
if(Physics.Raycast(ray, out hit, touchInputMask)){
GameObject recepient = hit.transform.gameObject;
if(touch.phase == TouchPhase.Began){
recepient.SendMessage("OnTouchDown",hit.point,SendMessageOptions.DontRequireReceiver);
}
if(touch.phase == TouchPhase.Ended){
recepient.SendMessage("OnTouchUp",hit.point,SendMessageOptions.DontRequireReceiver);
}
if(touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved){
recepient.SendMessage("OnTouchStay",hit.point,SendMessageOptions.DontRequireReceiver);
}
if(touch.phase == TouchPhase.Canceled){
recepient.SendMessage("OnTouchExit",hit.point,SendMessageOptions.DontRequireReceiver);
}
}
}
}
}
}
Comment
Answer by JayOhhh · Jul 10, 2014 at 09:03 PM
If you want it to work on 2D colliders you need to change the following line to use 2D ray casting:
if(Physics.Raycast(ray, out hit, touchInputMask)){
http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
Your answer
Follow this Question
Related Questions
Raycast Hit not working 0 Answers
Why in Unity3D RaycastHit. textureCoord always return 0,0 after building the project? 1 Answer
Rays not hitting (most of the time) 0 Answers
Touch not working on guiTexture. 1 Answer
Moving a 3D object with 2D swipes 2 Answers