How do you make a visual Raycast?

I want to make it so that my player can see a Raycast instead of it just being invisible so I can get a visual feel of what it looks like.

How would I do this?

Create a part and set its ‘CFrame’ property to one constructed by the CFrame.lookAt() constructor and set its length to that of the ray’s distance, then shift the part by half its size along the necessary axis (should be Z).

1 Like
local function VisualizeRay(origin,hit) -- origin = start position of ray, hit = hit position of ray
	local mag = (origin - hit).magnitude -- magnitude between points
	local VisualizePart = Instance.new("Part")
	VisualizePart.Anchored = true
	VisualizePart.CanCollide = false
	VisualizePart.Size = Vector3.new(0.2, 0.2, mag)
	VisualizePart.CFrame = CFrame.lookAt(origin, hit) * CFrame.new(0, 0, -mag/2)
	VisualizePart.Color = Color3.new(1, 0, 0)
	VisualizePart.Material = Enum.Material.Neon
	VisualizePart.Parent = workspace.Terrain
end
4 Likes

Could you possibly put comments on the code so I can understand It? I don’t really understand much about CFrame.LookAt and origion and hit.

  • CFrame.LookAt is the same as CFrame.new, the only difference is that CFrame.new is deprecated and its a good practice to use (since its more optimized).
  • origin is the raycast start position (the first argument when you use workspace:Raycast), you just pass it trough the function call.
  • hit is the hit position of the ray (ray.Position).
1 Like

If my ray is going down, ( 0, -10, 0 ), would I put

	VisualizePart.Size = Vector3.new(0.2, mag,  0.2)

And could you explain why you did CFrame.lookAt(origin, hit) * CFrame.new(0, 0, -mag/2)?

No since i make the part face the end point (The Front Face being Z axis when resizing)

Here i use the CFrame.lookAt to put the part at the ray start position and make its orientation point at the raycast hit position, then i multiply by half the magnitude so i position the part at the middle of the two points

1 Like

you can use a Beam

https://create.roblox.com/docs/building-and-visuals/lighting-and-effects/beams

you just need 2 parts with attachments and position 1 part at the start of the ray and 1 part at the end of the ray

you can see how it will look here

3 Likes

It works but, I had to add a destroy at the end after a few miliseconds because it spammed so many parts.

1 Like