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). 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.
Calculating Direction From an Origin and Destination »
When applicable, an unknown direction vector 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:
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.
If the raycasting operation hits an eligible
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.
|RaycastResult.Position||The world space point at which the intersection occurred, usually a point directly on the surface of the instance.|
|RaycastResult.Normal||The normal vector of the intersected face.|