We use cookies on this site to enhance your user experience

Raycasting: How it Works

Raycasting: How it Works

Aug 29 2019, 9:22 AM PST 2 min

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


Let’s say you want to make a ray-casting laser gun. 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 functions are coded in C++. Algorithms made in C++ tend to be much more efficient, and thus faster. The release of the built-in raycasting algorithm proved to be 105 times faster than the most efficient known user-created raycasting algorithm.


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), the position returns the center of the ray and the normal returns the normal of the surface the ray hit (if it hit any).

In coding terms:

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