Touch to Ray on Canvas

Hi, all!

I’m using some simple code to see if I’m tapping on an object using Camera.main.ScreenPointToRay.

This has always worked in the past for me. However, this time, all of my touches appear in the relative canvas space instead of the objects I want to touch! What gives?

Here’s the code that is placed on the main camera which is orthographic

	void Update () {
		if( Input.touches.Length > 0 ){
			Touch myTouch = Input.touches[0];
			Ray myRay = Camera.main.ScreenPointToRay( myTouch.position );
			RaycastHit hit;
			Debug.DrawRay( myTouch.position, Vector3.right, Color.red, 10.0f, false );
			if( Physics.Raycast( myRay, out hit, 10.0f, myMask )){
				if( hit.transform.tag == "Door" ){
					Debug.Log ( "Touched a door!" );
				}
			}
		}
	}

The touches appear on the canvas instead of the camera world space ( The camera is selected. I had to zoom out a lot ).

47580-screen-shot-2015-06-03-at-112456-am.png

Thanks! - YA

This is happening because you have all the objects (UI and the objects you want to touch on the same layer).
Try to make an UI layer, assign that layer to your UI objects.
In your raycast script, declare a public LayerMask object. In Inspector assign all the layers except the one for UI. Use Raycast method will all the parameters:

public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers);