I’m trying to make a pathfinding script where it will only chase the players if it raycasts from it’s humanoidrootpart and the final position is close to the player’s humanoidrootpart but it doesn’t seem to work because it’s not getting the correct direction vector3, help please!!
Old Description
I’m trying to make a pathfinding script where it will only chase the players if it raycasts from it’s humanoidrootpart and the final position is close to the player’s humanoidrootpart but it doesn’t seem to work… at all. Well it moves but the raycast just becomes nil and it doesn’t do anything, please help
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 10000
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("HumanoidRootPart")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) and not temp2:FindFirstChild("ZombieScript") then
if script.Parent.Configs.ChasesNPCs.Value == false and game.Players:GetPlayerFromCharacter(temp2) or script.Parent.Configs.ChasesNPCs.Value == true then
if (temp.Position - pos).magnitude < dist then
local vector = script.Parent.HumanoidRootPart.Position - temp.Position
if vector.magnitude < .001 then
vector = Vector3.new(0, 0, -1) -- default direction
else
vector = vector.unit
end
local ray = Vector3.new(9999,9999,9999)
task.spawn(function()
local raythin = RaycastParams.new()
raythin.FilterDescendantsInstances = {script.Parent}
local rayy = workspace:Raycast(pos, vector, raythin).Position
if rayy then
ray = rayy
end
end)
if (ray - temp.Position).Magnitude < 2.5 then
torso = temp
dist = (temp.Position - pos).magnitude
end
print(ray)
end
end
end
end
end
return torso
end
Please someone I’ve tried everything(?) and it just doesnt work
This piece of code here is part of the problem. You may think the Direction of the Raycast should be in unit form, but the Direction parameter also decides the range of the Raycast. This means as of right now, it will only check one stud in front of it. I would recommend just cutting out the entire 5 lines above.
Try this tutorial on how to make your rays visible (you have to use Ray.new with this tutorial). Maybe it could help you figure out where you ray is really going and why it’s returning nil. Obviously since the tutorial only works with Ray.new, you can just switch it back to workspace:Raycast after the problem is resolved.