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 more complex example follows the same logic for firing the raycasts, but first needs to calculate the spread.
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!