This may come as a shock to some of you, but most weapons in shooter games don’t actually shoot any bullets (gasp). It’s all behind the scenes magic. A sound effect plays, there are some particle flashes in front of the barrel, and animation of the player and weapon moving with kickback. If all that is true, how does anything get hit? This is where Raycasting comes in.
A Raycast is like an invisible line that goes in a specific direction and can be used to send a message. Think of it like a laser pointer. Previously, we have seen it used in 2D to determine if the player is grounded. The Raycast pointed down for a small distance and if it found something with the layer ‘Ground’, then the player knew it was grounded.
This time we are going to use a Raycast without a distance limit to simulate shooting a weapon. To know where we are aiming, we are first going to need a crosshair or any image in the center of the screen. Create an Image in the Hierarchy and anchor it in the center. This will help as a visual cue of where we are aiming.
Now let’s look at the code. We want to send out a Raycast from the camera’s center, right where the crosshair is, and go straight out. This will happen on a left mouse click. We are going to start with that in Update() and use it to call a function that will do the rest.
There are many ways to call a Raycast that you can look up. For this example, we are setting up a Vector3 for the center. Then, we are going to use that center and have it be used as the ray’s origin from the camera.
We also need to declare a RaycastHit. This stores the information based on what the Raycast actually hits. With that, we can use an IF statement and see whether or not something was hit. Put it all together and you have a Raycast call.
There are many more parameters and ways to set up your Raycast. You can add a specific distance. You can add a layer mask. You can even make Raycasts that are thicker than laser pointers.
Raycasts add many possibilities to your game design. Go and explore and make great things.