PcoWSkbVqDnWTu_dm2ix

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.

Origin

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

Direction

A ray’s direction is a datatype/Vector3 with a defined length (magnitude). When applicable, an unknown direction 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

In this sample project, the direction is calculated as so:

  1. rayOrigin is simply caster.Position.
  2. Rays are cast directly downward from the caster, so rayDestination is a datatype/Vector3 100 studs below the caster’s position. This also makes the ray’s length 100 studs and hit detection will only detect parts along that length.
  3. Based on the formula above, rayDirection = rayDestination - rayOrigin.

Casting

Once the origin and direction are determined, the ray is cast with the datatype/Ray|Ray.new() constructor:

Hit Detection

On its own, a ray doesn’t detect BasePart|BaseParts or Terrain along its length, so WorldRoot/FindPartOnRay|FindPartOnRay() is called for hit testing. The first parameter is the datatype/Ray object and the optional second argument of caster.Parent tells the function to ignore the caster’s parent (LaserCaster model) and all of its descendants.

To test for a hit, simply check that hitPart is not nil. Additionally, you can test for game-specific logic using any property of the object like hitPart.Parent.


This concludes the intro to raycasting. For further exploration, see WorldRoot/FindPartOnRayWithWhitelist|FindPartOnRayWithWhitelist() and WorldRoot/FindPartOnRayWithIgnoreList|FindPartOnRayWithIgnoreList(), variants of WorldRoot/FindPartOnRay|FindPartOnRay() that let you whitelist or ignore multiple objects and their descendants.

Tags:
  • raycast
  • detection
  • hit
  • sight