Unity : How to Raycast a Touch/Tap

Posted by matheus@guimak.com |15 Sep 17 | 0 comments

version Unity 2017.2

Raycasting is actually pretty simple. You pick a point in your worldspace and instruct Unity to cast an invisible laser beam from a camera to that point. The code is not necessarily intuitive, but still easy.

The recipe:

Create an InputManager class or whatever MonoBehaviour you may want to use to watch for user interaction with the screen. In the Update method check for a single touch.

If we want to do something every time the user taps on the screen then we can just add our code after this check and we’d be done. However, if we want to react differently depending on what the player is tapping then we need to raycast – that means firing off an invisible laser beam from a given camera to a given position in the world space and checking if it hits anything on its way. then we can check the property of what it has hit in order to determine if it is something we want to react to.

Let the code speak for itself:

void Update()

{

if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) //has the user tapped the screen?

{

var pos = Input.GetTouch(0).position; //where have they tapped on the screen?

var worldSpacePos = Camera.main.ScreenToWorldPoint(pos); //how does that translate to our world coordinates?

 

 

RaycastHit2D hit = Physics2D.Raycast(worldSpacePos, Vector3.forward, Mathf.Infinity); //cast an invisible beam straight through from our world coordinate forward all the way to infinity

 

if (hit.collider == null) // did it hit anything?

{

return; //woh woh woh… ignore it.

}

 

if (hit.transform.gameObject.tag == “enemy”) //it’s hit something! is it what I want?

{

//yes! we’ve tapped on an enemy. KILL IT!

var enemy = hit.transform.gameObject.GetComponent<Enemy>();

enemy.Die();

}

}

}

 


Leave a Reply

Your email address will not be published. Required fields are marked *