Raycast
Casts a ray using an origin, direction, and optional datatype/RaycastParams
. If it finds an eligible BasePart
or Terrain
cell, a datatype/RaycastResult
is returned containing the results of the operation. If no datatype/RaycastParams
object is provided, the defaults are used (all parts are considered and Terrain
water is not ignored).
Note that the length (magnitude) of the directional vector is important, as objects/terrain further away than its length will not be tested. If you’re using a datatype/CFrame
to help create the ray components, consider using CFrame.LookVector
as the directional vector and multiply it by the desired length as shown in the example below.
For a demonstration of how raycasting works, see the articles/Raycasting|Intro to Raycasting
article.
datatype/Ray
object, but its origin and direction components can be borrowed from Ray.Origin
and Ray.Direction
.
Parameters
Name | Type | Default | Description |
---|---|---|---|
|
The origin point of the ray. |
||
|
The directional vector of the ray. Note that the length of this vector matters, as parts/terrain further away than its length will not be tested. |
||
RaycastParams{IgnoreWater=false, CollisionGroup=Default, FilterDescendantsInstances={}}
|
An object used to specify hit eligibility in the raycast operation. If not provided, default values are used where all parts are considered and |
Returns
Return Type | Summary |
---|---|
Contains the results of a raycast operation, or |
Code Samples
Basic Raycasting
The following example shows how to construct a datatype/RaycastParams
object, use it in a raycasting operation, and check the results. For a more in-depth demonstration of how raycasting works, see the articles/Raycasting|Intro to Raycasting
article.
-- Build a "RaycastParams" object
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Whitelist
raycastParams.FilterDescendantsInstances = {workspace.Model}
raycastParams.IgnoreWater = true
-- Cast the ray
local part = workspace.Part
local raycastResult = workspace:Raycast(part.Position, part.CFrame.LookVector*50, raycastParams)
-- Interpret the result
if raycastResult then
print("Object/terrain hit:", raycastResult.Instance:GetFullName())
print("Hit position:", raycastResult.Position)
print("Surface normal at the point of intersection:", raycastResult.Normal)
print("Material hit:", raycastResult.Material.Name)
else
print("Nothing was hit!")
end