Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why do I only get nil on a raycast?

Hello, I have a guard that is supposed to detect things from a raycast. I have a small invisible part that is anchored in front of the guard. Everytime I go infront of the guard it just prints nil.

Here is the code

local reactiontime = 1
local dir = script.Parent.Dir.Dir
local head = script.Parent.Head
local loop = 0
local distance = 50

while script.Parent.Humanoid.Health > 0 do
	wait(reactiontime)
	print("Looking")
	loop = loop + 1
	local lookray = workspace:Raycast(head.Position, dir.Position * distance)
	print(lookray)
end

Could anyone please tell me why it only prints nil?

1 answer

My assumption is that you are doing the raycast wrong, if the following doesnt help then I don't know what to tell you.

The :Raycast() method accepts the parameters of a Ray Origin and a Ray Direction, meaning that the first argument of :Raycast() should be the position, and the second should be the direction. Where I think things are going wrong is with the direction.

Another thing to put into consideration is that :Raycast() may also be detecting the characters head by default as well. Use a RaycastParams object (https://developer.roblox.com/en-us/api-reference/datatype/RaycastParams)

ANOTHER thing: I am assuming is that the part dir's position is where your ray is trying to point to.

PS: Keep in note that the return of :Raycast() are that of RaycastResult type. (https://developer.roblox.com/api-reference/datatype/RaycastResult)

To do this (properly):

local lookResults = workspace:Raycast(head.Position, (dir.Position - head.Position).Unit * distance)

This discussion is preserved as it was. New answers, comments, and votes are closed.