Raycasting

From Legacy Roblox Wiki
Jump to navigationJump to search

Raycasting describes the act of casting a ray from a certain point in a certain direction, and determining what it collides with.

Uses

Let's say you want to make a gun that shoots out lasers. Okay, we created the base LocalScript. Now, we make the laser. The question is this: where does the laser beam stop? We were given a raycasting function in mid-2011, (Workspace::FindPartOnRay). Before that, we had to create our own raycasting algorithms.

You might be asking, why did Roblox create it for us when we already had it? Well, built-in events are coded in C++. Algorithms made in C++ tend to be much more efficient and of course, faster. The release of the built-in raycasting algorithm proved to be 105 times faster than the most efficient known user-created raycasting algorithm.

Usage

FindPartOnRay( Ray ray, Instance ignoreDescendentsInstance, Bool TerrainCellsAreCubes )
Returns BasePart object, Vector3 position
Description: Returns the first part that intersects with a ray.
Member of: Workspace


In more in-depth definitions, the ray is a ray object that has stored the origin and direction of the ray. ignoreDescendentsInstance is an instance value that makes it so that, when the ray is created, it will not be obstructed by the descendants of the instance passed to it. The method returns the object the ray hit (if it exists, otherwise, it returns nil) and the position returns the center of the ray.

In coding terms:

local ray = Ray.new(
    Weapon.Handle.CFrame.p,                           -- origin
    (mouse.Hit.p - Weapon.Handle.CFrame.p).unit * 500 -- direction
) 
local ignore = game.Players.LocalPlayer.Character
 
local hit, position = Workspace:FindPartOnRay(ray, ignore)

See also