Hello Roblox Devs,
I have attempted to make a pathfinding script that will find a player within a certain distance. Unfortunately, it does not work.
What did i do wrong?
Code:
local PositionTorso = script.Parent.Torso.Position
local NPC = script.Parent -- If your script is inside the NPC.
NPC.PrimaryPart:SetNetworkOwner(nil)
local PathfindingService = game:GetService("PathfindingService")
local pathParams = {
AgentHeight = 5,
AgentRadius = 3,
AgentCanJump = true,
}
local function getPath(destination)
local path = PathfindingService:CreatePath(pathParams)
path:ComputeAsync(script.Parent.HumanoidRootPart.Position, destination.Position)
return path
end
function findNearestTorso(pos)
local list = game.Workspace.Players:GetChildren()
local torso = nil
local dist = 110
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("UpperTorso")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
local humanoid = script.Parent.Hum
while wait(0.01) do
PositionTorso = script.Parent.Torso.Position
local target = findNearestTorso(PositionTorso)
print(target)
local path = getPath(target)
if target ~= nil then
--script.Parent.Random.Value = false
if path.Status == Enum.PathStatus.Success then
for i, waypoint in pairs(path:GetWaypoints()) do
path.Blocked:Connect(function()
path:Destroy()
print("Blocked")
end)
if target.Humanoid.Health > 0 then
lastPos = target.HumanoidRootPart.Position
break
else
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
if lastPos then
humanoid:MoveTo(lastPos)
humanoid.MoveToFinished:Wait()
lastPos = nil
break
else
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait()
end
end
end
else
return
end
else
--script.Parent.Random.Value = true
end
end