I wrote this script from a tutorial, which helps with touch.Inputs. The problem is, the raycasts are 3d, but my game is 2D. I tried different ways to convert the raycasts in the script to 2d, but nothing have worked.
Can someone tell me how to need to be converted?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TouchInput : MonoBehaviour {
public LayerMask touchInputMask;
private List<GameObject> touchList = new List<GameObject>();
private GameObject[] touchesOld;
private RaycastHit hit;
// Update is called once per frame
void Update () {
#if UNITY_EDITOR
if(Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0)) {
touchesOld = new GameObject[touchList.Count];
touchList.CopyTo(touchesOld);
touchList.Clear();
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,out hit,touchInputMask)) {
GameObject recipient = hit.transform.gameObject;
touchList.Add(recipient);
if(Input.GetMouseButtonDown(0)) {
recipient.SendMessage("OnTouchDown", hit.point, SendMessageOptions.DontRequireReceiver);
} if(Input.GetMouseButtonDown(0)) {
recipient.SendMessage("OnTouchUp", hit.point, SendMessageOptions.DontRequireReceiver);
} if(Input.GetMouseButtonUp(0)) {
recipient.SendMessage("OnTouchStay", hit.point, SendMessageOptions.DontRequireReceiver);
}
}
foreach (GameObject g in touchesOld) {
if(!touchList.Contains(g)) {
g.SendMessage("OnTouchExit", hit.point, SendMessageOptions.DontRequireReceiver);
}
}
}
#endif
}
}
I've never worked with Raycast or touch, but would it be [Physics2D.Raycast][1] rather than Physics.Raycast? [1]: https://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
– Ninjapro2kThere is a version of raycast which accepts an origin and a direction, you just convert your ray into 2 vector2s. e.g Vector2 rayOrigin = new Vector2(ray.origin.x, ray.origin.y); Vector2 rayDirection = new Vector(ray.direction.x, ray.direction.y); then use like if(Physics.Raycast(rayOrigin, rayDirection, out hit, mathf.infinity, touchInputMask)) { //blah }
– roman_seditionAdd
– ShadyProductionsDebug.Log("Collided with " + other.gameObject.Name);in the collision so we know you are actually triggering the collision. Also the collider should not be a 2d collider, nor trigger. Also use lowercase gameObject:other.gameObject.tag