Shooting With Raycasts

Jack Leavey
2 min readOct 6, 2022
A raycast is fired along the laser sight, dealing damage when it collides with a properly tagged gameobject.

A raycast is an invisible line that moves in a direction from an origin point until it collides with an appropriate object. Many games utilize this method for creating “hit-scan” firearms.

In this example, a raycast is originating from the end of the handgun and firing forward. If it collides with a specific gameobject, it will trigger logic on that gameobject. In this case, it triggers a damage function, which lowers the enemy’s health. When that health reaches 0, the enemy dies.

Above is the basic logic for firing the raycast itself. I set the origin point, the origin direction, and output hit, and finally left the length at infinity. If it collides with a collider, it looks for a function named “damage” and then applies the integer value gunDamage to that logic.

This function is called anytime the raycast collides with an enemy.
In a more complex example, the shotgun fires an array of 8 raycasts, with randomized angles. This leads to a random spread with each shot, creating a cone of fire.

This more complex example follows the same logic for firing the raycasts, but first needs to calculate the spread.

This function sets the parameters for the spread of the shotgun.
This function establishes that the shotgun should fire 8 raycasts, each one adhering to the cone of fire.

That’s all for a simple raycast system. Raycasts can be used for many other systems, including menus, triggers for items, dialogue, etc. With a little fine tuning, raycasts make for excellent tools to create instant damage firearms!



Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!