Simple Raycasting problems

The Problem

To be honest their isn’t really a problem, only thing is, is that my console is spitting out “attempt to call a nil value” like crazy and whenever I step between the what the ray origin and target the ray goes right through me and doesnt stop on me like how I want it to.

Console

My script

--// Services
local RunService = game:GetService("RunService")


--// Misc
local LASER_THICKNESS = 0.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
	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())

Weird how it errors and doesnt tell where it does.
In your code when u call castRay function RunService.Stepped:Connect(castRay())
i think u dont need extra () in there so just RunService.Stepped:Connect(castRay) should work?
Maybe it fixes that?

2 Likes

Thank you so much I would of never thought that was the problem!

1 Like

Im happy it worked!
No problem

1 Like