Shooting Things with Unity’s Physics Raycast

You Can Use A Laser to Make Your Lasers Work

Micha Davis
2 min readJun 10, 2021
Pew pew pew!

Today I’ll be adding the ability for the player to shoot targets in a 3D game using Unity’s Physics.Raycast() method.

To start, I’ll throw a debugging ray into the scene so we can tell where the camera is looking.

Since the camera’s forward direction is our look direction, this should give us a nice indicator for our aim in the Scene View. For the Game view, I’ll toss a UI Canvas Image up and anchor it to the center of the screen. If both of these match, then I’ll know my raycast is set up correctly and I can implement the input actions.

The Fire action is a Button action bound to the Mouse Left Button.

And the OnFire() method is where the magic happens. I don’t have a damage interface set up yet, so for now I’m just going to collect the name of the object I hit with my raycast. The C# syntax for that is:

Pardon the multiline formatting of the If conditional — this is formatted to fit the article width while staying easily readable

So, stepping through: if the fire cooldown is past AND the ray we cast from the camera in the camera’s forward direction out into infinity hits something, then we will reset the fire cooldown and log the name of the object we hit.

Let’s take a look.

Success.

Tomorrow we’ll set up some zombies to shoot. Thanks for reading!

--

--

Micha Davis

Unity Developer / Game Developer / Artist / Problem Solver