Roblox Studio · Lesson 22

Ray detection: build a distance detector

Use Raycast to send out an invisible detection line, filter itself and read hit objects, locations and distances.

10–15 years old 75 minutes Raycast / RaycastParams Hands-on practice Testing and Saving

Course overview

Send out an invisible line to find the first obstacle ahead.

Without actually throwing a block, you can also know whether there is a wall ahead. Raycast checks in one direction from the starting point, returning the first object encountered.

This is a ranger, not a weapon. You can read distance and draw results with a fine light to help you understand the vector.

01 · BEFORE

Before starting

Understanding Vector3, Part, and nil checks. Create a new Lesson22 Baseplate.

02 · MAKE

Your work

A Sensor that detects 50 studs forward, and the Output displays the hit object and distance.

03 · CHECK

Complete flag

Hit the wall when there is a wall, and return nil when there is no wall; changing the length will change the detectable range.

The auxiliary line sent by the Sensor is connected to the TargetWall, and the hit distance of the Output is 19.5
Figure 22-1 · Studio real shot: The auxiliary line stops on the near surface of TargetWall, and the Output displays Hit: TargetWall Distance: 19.5. Note that what is measured is the surface, not the center of the wall.

Learning route

Prepare first, then do it; after seeing the result, remember to save it.

Every time a small step is completed, it is tested. Say what you expect to see first, and then use Play and Output to check it. Don't rush to write all the code at once.

1

01 · Place the detector and the wall at the same height

Let's start with the most predictable arrangement: detector at Z=-4, wall at Z=-24, both at X=0. The detection direction is the Sensor's local front, which is the LookVector.

2

02·The direction vector also contains length

The length of LookVector itself is about 1, multiplied by 50 to detect 50 studs. The second argument to Raycast is not the endpoint coordinate.

3

03· Filter yourself and draw the inspection results

RaycastParams is used to exclude Sensor to avoid detecting itself. When the result is nil, you cannot continue to read result.Instance and must branch.

4

04 · Collision and query are different switches

CanCollide determines physical obstruction, and CanQuery determines whether it can participate in spatial query. A decoration that does not collide may still be detected by the ray.

5

05 · Use three pendulum methods to verify your predictions

Ranging returns the first hit surface, rather than always penetrating the scene to find the target name. Add a box in front and the result should be a box.

Step by step

01 · Place the detector and the wall at the same height

Let's start with the most predictable arrangement: detector at Z=-4, wall at Z=-24, both at X=0. The detection direction is the Sensor's local front, which is the LookVector.

By default Organization=0,0, 0, 0, 0, lookVector to negative Z. Switching Sensor will also change the direction of the ray, and position and direction will not be confused with direction.

  1. Create Sensor: Size=2,2,2, Position=0,4,-4, Orientation=0,0,0, Anchored=true.
  2. Create TargetWall: Size=8,8,1, Position=0,4,-24, Anchored=true, CanQuery=true.
  3. Create DistanceProbe in ServerScriptService.

Step by step

02·The direction vector also contains length

The length of LookVector itself is about 1, multiplied by 50 to detect 50 studs. The second argument to Raycast is not the endpoint coordinate.

If the starting point origin and the end point target are known, the direction vector should be target - origin. If you pass the target directly, you may get another completely different ray.

  1. First mark the starting point, direction and maximum length on the paper.
  2. The projected close surface distance at which the wall will be set down by default is approximately 19.5 studs instead of the center 20 walls.

Step by step

03· Filter yourself and draw the inspection results

RaycastParams is used to exclude Sensor to avoid detecting itself. When the result is nil, you cannot continue to read result.Instance and must branch.

The visible thin lines are the additional Parts we created and are not automatically generated by Raycast. It is set to CanQuery=false to avoid being blocked by its own auxiliary lines when probing again in the future.

  1. Put the complete code into DistanceProbe.
  2. Wait about three seconds after Play, read the Output and observe the auxiliary line.
  3. Don't stand between the Sensor and a wall when testing; otherwise it may detect your character first.
ServerScriptService > DistanceProbe · Complete scriptLuau
local sensor = workspace:WaitForChild("Sensor")
local MAX_DISTANCE = 50
task.wait(3)
local origin = sensor.Position
local direction = sensor.CFrame.LookVector * MAX_DISTANCE
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude
params.FilterDescendantsInstances = {sensor}

local result = workspace:Raycast(origin, direction, params)
local finish = origin + direction
if result then
    finish = result.Position
    print("Hit:", result.Instance.Name, "Distance:", result.Distance)
else
    print("Nothing within", MAX_DISTANCE)
end

local distance = (finish - origin).Magnitude
if distance > 0 then
    local line = Instance.new("Part")
    line.Name = "ProbeLine"
    line.Anchored = true
    line.CanCollide = false
    line.CanTouch = false
    line.CanQuery = false
    line.Material = Enum.Material.Neon
    line.Color = Color3.fromRGB(70, 220, 230)
    line.Size = Vector3.new(0.12, 0.12, distance)
    line.CFrame = CFrame.lookAt(origin, finish) * CFrame.new(0, 0, -distance / 2)
    line.Parent = workspace
end

Step by step

04 · Collision and query are different switches

CanCollide determines physical obstruction, and CanQuery determines whether it can participate in spatial query. A decoration that does not collide may still be detected by the ray.

This lesson does not damage the hit object, nor does it delete the wall. Clarify the measurement results first, and then connect the results to other gameplay methods.

  1. After Stop, move the wall to X=20 and play again. The wall should not be hit.
  2. Change MAX_DISTANCE to 10 and the wall should not hit when it is still 20 studs away.
  3. To test Can Query=false, turn the wall on CanCollide=false and close Can Query.

Step by step

05 · Use three pendulum methods to verify your predictions

Ranging returns the first hit surface, rather than always penetrating the scene to find the target name. Add a box in front and the result should be a box.

Don't create auxiliary lines infinitely every frame just to keep updating the distance. Continuous probing requires reusing objects, controlling frequency, and cleaning up resources that are no longer in use.

  1. Wall directly ahead: Hit TargetWall.
  2. Wall moves aside: don't hit it.
  3. Add a box in the middle: hit the box first, the distance is shorter.
View the Output window reference used when Raycast returns results
Figure 22-2: Official Output control reference: When testing the three swing methods, compare the hit object and distance one by one, and do not regard the previous round of records as a new result.Roblox Creator Documentation · CC BY 4.0 · The original image has not been modified · Description of the permit

Homework

It's your turn to change and make your own version.

1 Three times ranging

(b) Record the object name and distance in three cases: walls, open areas and boxes.

2 Turn around.

Rotate the Sensor 90° around the Y axis and reposition the wall to the new front.

3 Choosing: Altimeter Down

Change the direction to Vector3.new(0,-20,0) and measure the distance from the Sensor to the ground.

Completion criteria:First verify the work in Playtest, then click Stop and save it as "Initials_Lesson22" or the corresponding Homework copy; do not overwrite the runnable version of the previous lesson.

Exit questions

Answer it yourself first, and then expand on it.

Is the second parameter the end point?

No, it is a direction vector with length; when the end point is known, use the end point minus the starting point.

Why should we determine whether result exists?

If there is no hit, nil will be returned and nil.Instance cannot be read.

Is the light in the picture provided by Raycast?

No, it is an auxiliary part created by the script.

Why does the auxiliary line turn off CanQuery?

Avoiding a follow-on ray hit its own visual support.

Explore further

This is where we start when we need to check the data.

The text code can be copied directly. First confirm the script type, placement, and whether this code is a complete version or a small experiment; do not run multiple versions of the same script superimposed. The source of the interface reference picture has been marked. The object names in the picture may be different from those in this lesson. Please refer to the operation steps.

Download the code and placement instructions for this lesson