Intro to Raycasting

Intro to Raycasting

10 min

At its most basic level, raycasting is the act of sending out an invisible ray from a datatype/Vector3 point in a specific direction with a defined length. Once cast, you can detect if the ray hits a BasePart or Terrain cell.

Sample Project

The remainder of this article shows one solution for finding origin and direction vectors. To follow along, open the Laser Maze sample project in Studio before proceeding.

In this game, lasers are fired by floating orbs. Platforms touched by the lasers are temporarily destroyed.

Once the place is open:

  1. In the Explorer window, locate one of the LaserCaster models.
  1. Expand the model’s tree, locate the CasterMain script, and open it.

Casting a Ray

All of the raycasting logic in the CasterMain script is handled in the fireLaser() function on line 39.


A ray’s origin is simply a datatype/Vector3 point in the world. In this case, caster.Position is the origin of the ray.


A ray’s direction is a datatype/Vector3 with a defined length (magnitude). In this sample project, rays are cast directly downward from the caster, so rayDirection is a datatype/Vector3 pointing 100 studs down on the Y axis.

When applicable, an unknown direction vector can be calculated using a known origin and destination as follows:

  1. The origin plus a directional vector indicate the ray’s destination.
rayOrigin + rayDirection = rayDestination
  1. The origin is subtracted from both sides of the equation:
rayOrigin + rayDirection - rayOrigin = rayDestination - rayOrigin
  1. The ray’s direction is the destination minus the origin:
rayDirection = rayDestination - rayOrigin


Once the origin and direction are determined, the ray is cast with the WorldRoot/Raycast|WorldRoot:Raycast() function. This function also accepts an optional datatype/RaycastParams object which, in this sample, tells the ray to ignore (blacklist) the caster’s parent (LaserCaster model) and all of its descendants.

Hit Detection

If the raycasting operation hits an eligible BasePart or Terrain cell, a datatype/RaycastResult object is returned containing the results. To test for a hit, simply check that raycastResult is not nil and utilize the following properties as needed.

Property Description
RaycastResult.Instance The BasePart or Terrain cell that the ray intersected.
RaycastResult.Position The world space point at which the intersection occurred, usually a point directly on the surface of the instance.
RaycastResult.Material The enum/Material at the intersection point. For normal parts this is the BasePart/Material; for Terrain this can vary depending on terrain data.
RaycastResult.Normal The normal vector of the intersected face.
  • raycast
  • detection
  • hit
  • sight