Using a raycast to create a first person shooting mechanic in Unity.

Today we started by implementing a reticule in our game. First by installing the GameDevHQ hub, and then downloading a reticule set. For the stuff we’ve covered before, I’m going to go over quickly.

I chose Reticule #6. To implement it, I created a UI image, set it to the center by zeroing out its x and y positions, slid the sprite into the source image. It was recommended to resize the image to 64x64, but I felt 48x48 was more appropriate.

Next, we were given the challenge to clamp the camera so we don’t accidentally shoot our player.

So looking at the camera object as it hits the top of the players head, it looks like 17 degrees will be the absolute limit initially. For looking up, we’ll have to limit it to 0 for now.

We’ve already got some clamping going on, but let’s create some new variables for the y-clamping.

Now we get back into the camera look system and use our clamp function to limit the camera rotation around the x axis.

While I would have liked to have allowed the camera to go up and beyond 0, for some reason, the camera will reset. A bit of research has shown this has to do with the Euler to Quaternion conversions but I haven’t been able to find a successful fix yet. When I do, I’ll write an article on it. In the meantime, we can adjust our camera to go a little more behind the player and we can give the illusion of a little more control to the player.

Next up, was a shooting challenge. It was suggested we create a new script so that’s what I did and I attached it to the player.

For a test, we made some test cubes to shoot, I named mine Yorgle, Grundle, and Rhindal.

And for the challenge, we were given these goals:

//left click to fire, cast a ray to the center of the screen.
//debug the name of the object you hit.

So for the raycast, a bit of preliminary searching brought me to Camera.ViewportPointToRay

and their example basically gives us the answer to the challenge! Let’s implement it!

First we define the camera, easy enough. Then in Update, we create a new raycast with the name of ray. the x and y being at .5 is the exact center of the screen. then we create a holder for what the raycast hits.

A little more explanation: 0x is the left side of the screen and 1 is the extreme right, while 0y is the bottom, and 1 is the top, so .5,.5 is the exact middle!

When the mouse button is pressed, we call upon the Physics.Raycast method:

Our origin is the ray, the out keyword tells the method to return a value in the hit variable. and if it hits something, the gameobjects name will be stored in hit, and we’ll print it in the Debug.Log.

Let’s see if it works!

Excellent! It even tells us when we’re shooting the floor!

I’d say this was a successful challenge! Next, we’ll get into enemies!

cartoonist, game artist, and wanabe gamedev.