Raycasting involves sending out a ‘ray’ and finding out what it hits. Raycasting is used by game developers to find the distance between players and another object, aiming, detecting nearby objects, and finding line of sight.

The code below is one example of using the Raycast method.

bool Raycast(Vector 3 origin, Vector3 direction, float distance, LayerMask mask);

There are a few parameters that this method takes. The first is the Vector3 origin or position of where the ray starts and can hold three floats (the x, y and z coordinates). The second, Vector3 direction, is the direction that the ray will travel. The third, float distance, is the distance that the ray will travel before it stops. The last parameter is mask, which specifies what layers will be hit by the ray. The distance and mask parameters are optional. If they are left out, the ray will travel forever and hit all objects.

The code below could be attached to a camera in your game and used to detect whether an object is in front of the camera.

void Update(){
 if (Physics.Raycast(transform.position, transform.forward, 20))
 print("Something is in front of the camera");

There is also another way that the Raycast method can be used. It can be used to find out which object the ray collided with. It can use a type of variable called a RaycastHit. Here is an example of what it can look like:

bool Raycast(Vector3 origin, Vector3 direction, out Raycast hit, float distance);

Where you see ‘out’, it means that whatever object was hit by the raycast will be stored in the ‘hit’ variable when the method finishes running.

Try it out

So let’s give Raycasting a go!

Step 1 – Create a new scene in your project and add a few 3D shapes around the main camera in your scene. The shapes should be close enough to the camera so you can see them clearly when you run the game.

Step 2 – Add at least three or four shapes that are spaced out nicely.

Step 3 – Create a new script called raycastingScript and attach it to your main camera. Add the following code to the Update method inside the script:

float xDirection = Input.GetAxis ("Mouse X");
float yDirection = Input.GetAxis ("Mouse Y");
transform.Rotate (-yDirection, xDirection, 0);
checkIfRaycastHit ();

Step 4 – Add the following code to your class (outside of all other methods i.e. not inside the Start or Update methods).

void checkIfRaycastHit(){
 RaycastHit hit;
 if(Physics.Raycast(transform.position, transform.forward, out hit)){
 print (hit.collider.gameObject.name + " has been destroyed!");
 Destroy (hit.collider.gameObject);

Step 5 – Now run the scene. You will notice that the mouse will now move the camera around. When you center the camera on each object in your scene, those objects will be destroyed and a message will be displayed in the console.

You could extend this game by adding a score or time variable and displaying the score on the screen (something covered in the next tutorial – Graphical User Interfaces!).