How can I make a Ray Visible?

Hello! Im trying to learn how to do Raycasting, How would I make a Ray Visible?

Im also a bit confused on how Raycasting even works.

2 Likes

There’s a simple way to make a ray visible.

local Part = workspace.Part

local function RayToPart(ray)
	local MidPoint = ray.Origin + ray.Direction/2

	local Part = Instance.new("Part")
	Part.Anchored = true
	Part.CFrame = CFrame.lookAt(MidPoint, ray.Origin)
	Part.Size = Vector3.new(1, 1, ray.Direction.Magnitude)
	Part.Parent = workspace

	return Part
end

local NewRay = Ray.new(Part.Position, Part.CFrame.LookVector*100)
local Result = workspace:Raycast(NewRay.Origin, NewRay.Direction)

RayToPart(NewRay)
  1. I get an error
  13:25:56.896  LookVector is not a valid member of Vector3  -  Server - Shoot:15
  13:25:56.897  Stack Begin  -  Studio
  13:25:56.897  Script 'Workspace.Turret.Base.Shoot', Line 15  -  Studio - Shoot:15
  13:25:56.897  Stack End  -  Studio
  13:26:08.680  0.5, 0.5  -  Server
  13:26:08.950  0.5, 0.5  -  Client
  1. Can you explain how the code works before just giving me an example?

My bad, wrote Position instead of CFrame.

Part.CFrame.LookVector*100

There’s no need to explain the code, it’s really simple and easy to read.

Its not easy for me to read, if I never figure out how Raycasting and this code works, Im always going to be asking for help in the future.

Well, you could check DevHub or a YouTube video. I can explain the code.

local Part = workspace.Part

local function RayToPart(ray)
    --this function takes the ray as a parameter. Below, it gets the midpoint.
	local MidPoint = ray.Origin + ray.Direction/2

    --below it creates the part and returns it. I'm sure you're familiar with properties
	local Part = Instance.new("Part")
	Part.Anchored = true
	Part.CFrame = CFrame.lookAt(MidPoint, ray.Origin)
	Part.Size = Vector3.new(1, 1, ray.Direction.Magnitude)
	Part.Parent = workspace

	return Part
end

--creating the ray. You could play around with the parameters given. You also need to know about raycastparams
local NewRay = Ray.new(Part.Position, Part.CFrame.LookVector*100)
--raycasts the ray
local Result = workspace:Raycast(NewRay.Origin, NewRay.Direction)

RayToPart(NewRay)
4 Likes