Nerd For Tech
Published in

Nerd For Tech

Raycast in Unity

Let’s take a look at how we can add in a crosshair, add in a limit to where our camera is able to move and use raycast for shooting our projectiles. To start, we are going to build in a crosshair to our game using an image on our canvas:

From here, we can view it in our game and make any adjustments to the size if we see fit:

With our crosshair at a size and style we like, next we need to create a method to limit how much we are able to move our camera vertically. In order to do this, we will want to make a couple adjustments to our code for moving the camera in a vertical motion, and create a clamp in which we have our limits that the crosshair is able to move:

With this method built in for our vertical movement, we are able to add in a limit in which we can move our camera. With this limit set, we can take a look at how it is within our game and see if any further changes are needed for it:

With this range, we still have a small view of the player on the screen, and at the same time our crosshair won’t hit the player, giving it a better 3rd person feel.
Next, let’s take a look at how we can use Raycast for shooting our targets. First, we will create a couple random targets to hit along with a new script for the shooting method:

What we have done here is told unity that we want our Ray to be cast from the center of the screen, represented by the Center vector. We are then telling Unity that we want the ray to tell us what it has hit. Now that this is in place, let’s take a look at how it is within the game:

Now that we have our shooting method in place, we can start taking a look at how we are going to build our enemy units for the game.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store