Unity Raycast Tutorial (Step by Step)

An introduction to Raycasting in Unity for 2D and 3D games.
unity raycast yapımı
Unity Raycast

Any interaction between two objects occurs at some distance. For one object to interact with another, regardless of the distance between them, it is necessary to draw a vector from the interacting object to the object that’s interacted with. To execute this interaction, we use Unity Raycast.

What is Unity Raycasting?

Briefly, Raycasting is the process of shooting an invisible ray from a point, in a specified direction to detect whether any colliders lay in the path of the array. The name is pretty self-explanatory in that sense. Imagine you want your character to shoot an object. The impact and distance traveled by the bullet are calculated and executed by Raycasting.

This action can be executed for both Unity 3D and Unity 2D games. We will examine the two in separate sections.

Raycasting for Unity 3D games

For 3D games in Unity the syntax of ray function looks like this:

A basic code for Raycasting in Unity 3D.

Let’s break down what each part defines:

Vector3 origin defines the point of origin for your ray. This point is stored as a Vector3, with an X, Y & Z position. This code is specific to Unity 3D games, all vectors will be handled in Vector3 because of the three dimensions of your game.

Vector3 direction determines the direction of our ray. Again, it’s a Vector3 to give our ray a dimension to travel in, different than the dimension of our point of origin.

float distance is the distance that our ray should travel from the point of origin in the direction we determined, as a float value.

int layerMask value is worth talking about, even if it’s not necessary. In your Unity 3D game, for the object, you are setting a ray for could ignore some specified objects while hitting the others. Int value helps you to tag what will be recognized. Rest will be ignored.

Rays from the camera

There are different ways to define the origin of our ray. Setting the mouse position as a point of origin is an easy and effective way to determine where your ray originates from. This will help us especially if we are working on a Unity 3D game.

First, you need to convert your mouse position to the world of Unity. Our mouse position is a property of the input class. All you need to do is use Input.mousePosition, this transports your position of mouse as input for you to use as your origin of raycast. Pretty straightforward, right?

Let’s continue with the example of writing a script for firing a gun. Here’s an example text for setting a ray from the camera/cursor:

Raycasting with mouse position is easy!

Don’t worry, your guy is here to explain. Comments are put into the code for you to use as a guide. Nevertheless, let’s break it down:

camera = Camera.main defines our main camera variable. the if (Input.GetButton(“Fire1”)) part is setting an if function which is triggers -pun intended- our ray if I pressed the “Fire” button. MoveWithRay()represents the movement of our ray.

our Input.mousePosition will be defined as a Vector3 for obvious reasons. See above.

I defined the camera.transform.position.z as mousePos.z, to add some depth.

Ray ray= camera.ScreenPointToRay(mousePos)) is the beauty here. We create our ray thanks to ScreenPointToRay. This is the trick of casting rays from the camera.

RaycastHit checks what happens when our ray collides with something on its way.

the if function following –if (Physics.Raycast(ray,out hit,100))– checks if our ray hits something at a distance of 100.

When the if condition is met, I do the following:

Vector3 move = hit point; (I defined a new variable since I’m not able to modify the hit point)

move.y = transformation.position.y; (I don’t want our ray to travel in Y dimension)
move.z = transformation.position.z;(I don’t want our ray to travel in Z dimension.)
transform.position = Vector3.MoveTowards(transform.position, move, speed) (define the move and speed variables to move the object)

Raycasting for Unity 2D games

While defining a ray for your Unity 2D game is very similar to doing so for Unity 3D, though the syntax has some minor changes:

unity raycast 2d code
The syntax is very similar to Unity 3D Raycast’s.

Vector2 origin defines the point of origin for your ray. This point is stored as a Vector2, with X & Y positions. This code is specific to Unity 2D games, all vectors will be handled in Vector2 because of the two dimensions of your game.

Vector2 direction determines the direction of our ray. Again, it’s a Vector2 to give our ray a dimension to travel in, different than the dimension of our point of origin.

float distance is the distance that our ray should travel from the point of origin in the direction we determined, as a float value.

int layerMask value is worth talking about, even if it’s not necessary. In your Unity 2D game, for the object you are setting a ray for could ignore some specified objects while hitting the others. Int value helps you to tag what will be recognized. Rest will be ignored.

This was for writing your 2D ray manually.

Mind the collusions when writing your code.

In this script, I created my ray automatically. You can script your ray in either way. Let’s talk about the properties of the script above:

Create2DRay() calls your function inside update.
private void Create2DRay()

RaycastHit2D hit= Physics2D.Raycast(transform.position, transform.right, 100) makes our ray to travel to right with the distance value of 100.
if (hit.collider != null) checks if our ray collides with anything on the way.

We print out the GameObject’s name which our ray hits with: Debug.Log(hit.collider.gameObject.name)

I hope this manual helps you to cast rays in your Unity 2D or Unity 3D game.

Stay informed in 5 minutes

We send the latest and exclusive reports for the mobile game industry to your email inbox.

    We won't send you spam. Unsubscribe at any time.

    Leave a Reply

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

    Related Posts