Hello, so I’ve been trying to make a model to learn basic raycasting to help other people out, but the problem is it wouldn’t work. It keeps giving me an error.
--This script was made by justen123568 for learning pourpses to raycasting
--//SERVICES
local Runservice = game:GetService("RunService")
--/MISC
local LASER_THICKNESS = .1
--The parts representing the start and end of our ray
local Originpart,TargetPart = script.Parent.RayOrigin,script.Parent.RayTarget
local laserPart = script.Parent.Laser
--This tells our raycast function what to ignore
local RayCastParameters = RaycastParams.new()
RayCastParameters.FilterDescendantsInstances = script.Parent:GetChildren()
RayCastParameters.FilterType = Enum.RaycastFilterType.Blacklist
local function CastRay()
local origin = Originpart.CFrame.Position
local target = TargetPart.CFrame.Position
local direction = (target - origin)
local results = workspace:Raycast(origin,direction,RayCastParameters)
--Makes sure that if 'results' don't exist we still give it a table with a position value
if not results then
results = {Position = target}
end
local distance = (results.Position - origin).Magnitude
laserPart.CFrame = CFrame.new(origin,target) * CFrame.new(0,0 -distance/2)
laserPart.Size = Vector3.new(
LASER_THICKNESS,
LASER_THICKNESS,
distance
)
end
Runservice.Stepped:Connect(CastRay)
–This script was made by justen123568 for learning pourpses to raycasting
–//SERVICES
local Runservice = game:GetService(“RunService”)
–/MISC
local LASER_THICKNESS = .1
–The parts representing the start and end of our ray
local Originpart,TargetPart = script.Parent.RayOrigin,script.Parent.RayTarget
local laserPart = script.Parent.Laser
–This tells our raycast function what to ignore
local RayCastParameters = RaycastParams.new()
RayCastParameters.FilterDescendantsInstances = script.Parent:GetChildren()
RayCastParameters.FilterType = Enum.RaycastFilterType.Blacklist
local function CastRay()
local origin = Originpart.CFrame.Position
local target = TargetPart.CFrame.Position
local direction = (target - origin)
local results = workspace:Raycast(origin,direction,RayCastParameters)
--Makes sure that if 'results' don't exist we still give it a table with a position value
if not results then
results = {Position = target}
end
local distance = (results.Position - origin).Magnitude
laserPart.CFrame = CFrame.new(origin,target) * CFrame.new(0,0 -distance/2)
laserPart.Size = Vector3.new(
LASER_THICKNESS,
LASER_THICKNESS,
distance
)
end
Runservice.Stepped:Connect(CastRay)
Your direction variable needs to be the Unit of target - origin
You can use local direction = (TargetPart.Position - OriginPart.Position).Unit
Oh yeah, thanks, this was very helpful, but also your script kept inverting it, so I used my original one and it worked. Thanks, I appreciate your time and effort.