Codectionary / Developer documentation / Luau

Raycasting and hit results

A raycast asks what a line segment intersects. Its direction vector includes the distance to search, not just a unit direction. A miss returns nil; a hit provides an Instance, position and surface normal. Filters determine what the query ignores.

Syntax

local hit = workspace:Raycast(origin, direction, parameters)

Examples

Find a surface below a point

Script in ServerScriptService in a baseplate place. The ray starts twenty studs up and searches thirty studs down. It prints the result only when a surface is found.

local origin = Vector3.new(0, 20, 0)
local direction = Vector3.new(0, -30, 0)
local hit = workspace:Raycast(origin, direction)
if hit then
    print(hit.Instance.Name, hit.Position, hit.Normal)
else
    print("No surface within range")
end

Exclude your character

LocalScript in StarterPlayerScripts. This is a local observation for presentation, not authoritative evidence of a hit. A competitive action needs server-side validation of origin, range and game state.

local Players = game:GetService("Players")
local character = Players.LocalPlayer.Character or Players.LocalPlayer.CharacterAdded:Wait()
local root = character:WaitForChild("HumanoidRootPart")
local parameters = RaycastParams.new()
parameters.FilterType = Enum.RaycastFilterType.Exclude
parameters.FilterDescendantsInstances = {character}
local hit = workspace:Raycast(root.Position, root.CFrame.LookVector * 40, parameters)
if hit then print(hit.Instance:GetFullName()) end

Best practices

  • Multiply a normalized direction by the intended range.
  • Handle nil before reading hit.Position or hit.Instance.
  • Streaming can make a client’s available geometry differ from the server’s; do not treat the client query as authoritative.

At a glance

Purpose
Typed scripting and Roblox development
File extension
.luau
Runs in
Luau host; Roblox engine examples require Roblox Studio
Usually used with
Roblox APIs and Studio

Specifications & further reading

Related Luau documentation