Intro to Raycasting
Intro to Raycasting
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
datatype/Vector3is the functional length (magnitude) of the ray. Anything past the directional vector will not be detected.
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:
- In the Explorer window, locate one of the LaserCaster models.
- 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). When applicable, an unknown direction can be calculated using a known origin and destination as follows:
- The origin plus a directional vector indicate the ray’s destination.
- The origin is subtracted from both sides of the equation:
- The ray’s direction is the destination minus the origin:
In this sample project, the direction is calculated as so:
- Rays are cast directly downward from the caster, so
datatype/Vector3100 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.
- Based on the formula above,
rayDirection = rayDestination - rayOrigin.
Once the origin and direction are determined, the ray is cast with the
On its own, a ray doesn’t detect
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.
WorldRoot/FindPartOnRay|FindPartOnRay()function returns the
Terraincell hit, the point of intersection, the surface normal at the point of intersection, and the associated
Enum/Materialhit. In this project, only the first two aspects are needed and are assigned to the
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
This concludes the intro to raycasting. For further exploration, see
WorldRoot/FindPartOnRayWithIgnoreList|FindPartOnRayWithIgnoreList(), variants of
WorldRoot/FindPartOnRay|FindPartOnRay() that let you whitelist or ignore multiple objects and their descendants.