RaycastResult Returning Nil when Intersecting

My AI uses raycasting to see if a player is within it’s sight. However, it’s being finnicky and for some reason the RaycastResult will return nil despite visualizing it and clearly seeing that the Raycast is intersecting an object.

I should clarify: the raycast does find the target and return the result, other times it does not.

function checkSight(target)
	local params = RaycastParams.new()
	params.FilterDescendantsInstances = {model}
	params.FilterType = Enum.RaycastFilterType.Exclude
	
	local direction = (HumanoidRootPart.Position - target.Position).Unit * 60
	
	local function showCast()
		local part = Instance.new("Part")
		part.Parent = workspace
		part.CanCollide = false 
		part.Anchored = true
		part.Size = Vector3.new(.1, .1, 60)
		local dir = direction
		part.CFrame = CFrame.new((HumanoidRootPart.Position + target.Position)/2, HumanoidRootPart.Position)
		game:GetService("Debris"):AddItem(part, 10)
	end
	
	local raycastResult = workspace:Raycast(HumanoidRootPart.Position, direction, params)
	
	if raycastResult then
		if raycastResult.Instance then 
			if raycastResult.Instance:IsDescendantOf(target.Parent:FindFirstAncestorWhichIsA("Model")) or raycastResult.Instance == target then
				return true
			end
		end
	end
	
	return false
end
2 Likes

workspace is not my variable, it’s a variable that’s an alternative to game.Workspace or game:GetService("Workspace").

Sorry, didn’t realize which part you wanted to raycast from.

So the raycast never works? Could you be a little more specific when you say its “finnicky”?

I think the problem is ray direction. The visualisation is alright but the ray points backwards.

local direction = (target.Position - HumanoidRootPart.Position).Unit * 60

v a - v b is a vector pointing from b towards a.

If I’m not mistaken, either reversing the vectors or negating the result should fix the issue.

(Side suggestion: declare showCast outside of the function and replace legacy wait() based Debris for task.delay().)

2 Likes

It works and it doesn’t, pretty much. I put in print statements earlier and at times, when nearby the target, it will have a result and other times it won’t.

Figured it was something silly. Thanks!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.