Apologies, I know the problems of raycast not detecting a collision has been asked hundreds of times on here. I’m an experienced developer (though relatively new to Unity) and have been hitting a brick wall on this for 3 days now, I’ve searched this and other forums and tried every solution I could find, but haven’t managed to get the raycast to detect a collision.
I’m trying to allow the user to drag their finger over a grid on a touchscreen device and be able to detect which grid spaces were hit by the moving touch. Sounds pretty simple!
The grid is a 2D grid in the z plane (i.e. it spans the xy axes) and the camera points at it in 2D mode, the project is set to 2D behaviour.
Here’s the details of one of the grid spaces.
Here’s the code that’s not working (I’ve left in the commented out lines that were an attempt at using Ray instead of Vector3)
void Update()
{
if(game.t == "type9")
{
if(Input.touchCount > 0 || Input.GetMouseButton(0))
{
Vector3 touchPosWorld, rayDirection;
// Ray ray;
if(Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.Android)
{
Touch touch = Input.GetTouch(0);
touchPosWorld = Camera.main.ScreenToWorldPoint(touch.position);
// ray = Camera.main.ScreenPointToRay(touch.position);
}
else
{
touchPosWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
// ray = Camera.main.ScreenPointToRay(Input.mousePosition);
}
// if (touch.phase == TouchPhase.Moved)
// {
RaycastHit hitInformation;
rayDirection = Vector3.forward;
Debug.Log("Position " + touchPosWorld.ToString() + "; Direction " + rayDirection.ToString());
// Debug.Log("Ray " + ray.ToString());
// if(Physics.Raycast(ray, out hitInformation))
if(Physics.Raycast(touchPosWorld, rayDirection, out hitInformation))
{
GameObject touchedObject = hitInformation.transform.gameObject;
Debug.Log("Touched " + touchedObject.transform.name + " " + hitInformation.transform.name);
}
// }
}
}
}
Here are the Project Settings for Physics
This will need to work on touch devices, however I need to test in the editor so have added some temporary code for that. The Debug.Log line that displays the position of the touch is working perfectly when clicking the mouse in the editor, but the collider is never hit (or at least the Debug.Log inside the if statement never produces a log entry).
I’m running Unity 2019.2.10f1 on MacOS 10.14.6
- I’ve tried using ray (ScreenPointToRay) instead of position and direction - same problem
- I’ve tried switching the ‘static’ checkbox on and off - makes no difference
- I’ve tried playing with the Physic Material (and having no material) - no difference
- I’ve tried making the collider 200x200 in the hope that some ray would hit - still nothing
- I’ve tried moving the object from UI to default layer - no change
I can only think that since this project has Default Behaviour Mode set to 2D that there’s something I need to do to make it work?
I’m at a total loss on what to try next, any help is very much appreciated.