Shooting With Raycast in Unity!

addam davis
2 min readJan 19, 2022

Objective: Create a shooting system with Raycast!

This is a first-person shooter; this means that one of the features we need our player to do is shoot. In a first-person shooter the player shoots through the center of the screen.

Let’s begin by creating something for the player to shoot. create 3 cubes.

The player script is getting a little long, so I create a new script “Shoot”

We need a method to check for a left mouse click.

To Raycast from the center of the screen we need to use Camera.ViewportPointToRay

The bottom-left of the camera is (0,0); the top-right is (1,1); the center is (0.5,0.5) So we set a local vector 3 to the center, then we set the viewport point to ray to that local variable.

Then we can simply check the Raycast hit and debug the name of the object.

Now you have the ability to shot. You can now add a health system, damage, or impact animations, whatever you want really. Don’t be afraid to experiment with your code and I’ll see you in the next tutorial.

--

--