Ray
A Ray is a half-line, that is finite in one direction, but infinite in the other. It can be defined by a 3-D point, where the line originates from, and a direction vector, which is the direction it goes in. The direction is similar to the lookVector of CFrame.
Often, it is useful to construct a Ray at one point directed toward another. There is no constructor defined for this intent, but it can be be done as follows:
local start = Vector3.new(...) local lookAt = Vector3.new(...) local ray = Ray.new(start, (lookAt - start).unit)
The Ray object's main purpose is to act as a basis for Ray casting. Its methods allow comparison of Ray against other 3-D points. Rays are also used in the FindPartOnRay method of the Workspace.
For example you can detect if a Ray intersects a sphere:
function intersectsSphere(ray, position, radius) return ray:Distance(position) <= radius end
To check if the mouse is pointing at a sphere (even if other things are in the way):
if intersectsSphere(mouse.UnitRay, sphere.Position, sphere.Size.X/2) then -- handle collision end
Constructor | Description |
---|---|
Ray.new(Vector3 Origin, Vector3 Direction) | Creates a new Ray with given Origin and Direction. |
Method | Description |
---|---|
Ray:ClosestPoint(Vector3 point) | Returns the closest point on the Ray to point. Note Rays are unidirectional. |
Ray:Distance(Vector3 point) | Returns the distance from point to ClosestPoint(point) |
Properties
All of these properties are read-only:
Property | Type | Description |
---|---|---|
Ray.Origin | Vector3 | The Origin position |
Ray.Direction | Vector3 | The Direction vector |
Ray.Unit | Ray | The Ray with a normalized Direction |
Limitations
Technically, the length of the direction vector does not matter. However most Ray methods assume it is 1, so direction is a unit vector. As a result, you will get incorrect results if you do not make the direction a unit vector, or use Ray.Unit.