× Phaseshift FCOM Tutorials

Raycast Basics

Learn Raycast basics

The below is when you want to do something when a sensor has been triggered within a particular range. This could be for predicting collisions between moving objects, and may want to trigger an avoiding action, or stopping the GameObject before a collision is made.

It's important that the rayStartPosition and the direction argument in the second parameter both originate from the same position, in this case rayStartPosition. 

This fires a raycast from rayStartPosition in the forward direction for a length of collisionSensorLength - 50 Unity units. (50 meters) 

Advanced usage and performance considerations

Raycasts can be a performance sink if used en masse and aren't restricted in some way. If raycast length and a layer mask is not used, the raycast will check for all collisions, with everything, for infinity. That's a lot. 

In this example we've used a layer mask which we've dubbed 'Units', this corresponds to a class called Layers with a constant variable called UNITS that is set to the int id of the respective layers. This ensures the raycast only listens for collisions with gameObject's that have colliders that are a part of the 'Units' layer. 

We've also restricted the length of the raycast. This improved performance by reducing the maximum amount of colliders the raycast could collide with.

If you need to create many raycasts at the same time we recommend checking out RaycastCommand to batch raycasts.


To explore more on these topics, check out the documentation:


Liked this article?

Please consider sharing!

Josh Lyell

Game Developer