Hi all,
I’ve recently encountered an issue while raycasting. I’m trying to create a realistic enemy detection range, and for that, I raycast a bunch of rays at a certain angle to see what they return. However, all rays return nil, despite there clearly being parts obstructing the rays. The script is located inside the default R6 dummy.
Here’s my code, and example pictures are provided below
local humanoid = script.Parent
local rootPart = script.Parent.PrimaryPart
local headPart = script.Parent.Head
local FOV = 135
local sight = 30
function randomWalk()
local rayOrigin = script.Parent.Head.Position
for i = 0, FOV do
local rayDirection = Vector3.new(headPart.Orientation.X, headPart.Orientation.Y - FOV/2 + i + 90, headPart.Orientation.Z)
local rayParameters = RaycastParams:new()
local testPart = Instance.new("Part")
testPart.Size = Vector3.new(100, 1, 1)
testPart.Anchored = true
testPart.Position = rayOrigin
testPart.Orientation = rayDirection
testPart.Parent = workspace
rayParameters.FilterDescendantsInstances = {script.Parent}
rayParameters.FilterType = Enum.RaycastFilterType.Exclude
local raycastResult = workspace:Raycast(rayOrigin, rayDirection, rayParameters)
if raycastResult ~= nil then
print(raycastResult.Instance, rayDirection)
else
print(raycastResult)
end
end
end
randomWalk()
And here’s what happens when ran, along with the output console:
The issue may be with rayDetection. the rayDirection is supposed to be a Vector3 value representing the direction and magnitude of the ray. but you’re setting the rayDirection to the orientation of the headPart.
local humanoid = script.Parent
local rootPart = script.Parent.PrimaryPart
local headPart = script.Parent.Head
local FOV = 135
local sight = 30
function randomWalk()
local rayOrigin = script.Parent.Head.Position
for i = 0, FOV do
local angle = math.rad(i - FOV/2)
local rayDirection = CFrame.new(headPart.Position, headPart.Position + headPart.CFrame.LookVector) * CFrame.Angles(0, angle, 0) * Vector3.new(0, 0, -sight)
local rayParameters = RaycastParams:new()
local testPart = Instance.new("Part")
testPart.Size = Vector3.new(100, 1, 1)
testPart.Anchored = true
testPart.Position = rayOrigin
testPart.Orientation = rayDirection
testPart.Parent = workspace
rayParameters.FilterDescendantsInstances = {script.Parent}
rayParameters.FilterType = Enum.RaycastFilterType.Exclude
local raycastResult = workspace:Raycast(rayOrigin, rayDirection, rayParameters)
if raycastResult ~= nil then
print(raycastResult.Instance, rayDirection)
else
print(raycastResult)
end
end
end
randomWalk()
This new script i did rotates the LookVector of the headPart around the Y by the specified angle, and uses it to create a direction vector for the raycast.
This is quite odd, but its hard to find an issue without testing.
From experience the main cause is the Direction used in the raycast.
CanQuery should be on for your parts