What do I want to achieve?
I wanna make improve this script so that the npcs using this script can go around obstacles instead of running into them.
What solutions have I tried so far?
i tried to use pathfinding myself but spent hours on it and failed miserably
Code:
local runAwayDistance = (math.random(200,300))
local humanoid = script.Parent:WaitForChild("Humanoid")
local OldHealth = humanoid.Health
function checkHRP()
local closest
local closestMagnitude = 25
for _, player in pairs(game.Players:GetPlayers()) do
if player.Character then
local hrp = player.Character.HumanoidRootPart
local hrpMagnitude = hrp and (script.Parent.HumanoidRootPart.Position - hrp.Position).Magnitude or math.huge
if closestMagnitude >= hrpMagnitude then
closestMagnitude = hrpMagnitude
closest = hrp
end
end
end
return closest
end
while wait() do
local torso = checkHRP()
humanoid:GetPropertyChangedSignal("Health"):Connect(function()
if humanoid.Health < OldHealth then
script.Parent.Humanoid:MoveTo((CFrame.new(script.Parent.HumanoidRootPart.Position) * CFrame.new(0,0, runAwayDistance)).Position)
end
end)
if torso then
script.Parent.Humanoid:MoveTo((CFrame.new(script.Parent.HumanoidRootPart.Position, torso.Position) * CFrame.new(0,0, runAwayDistance)).Position)
humanoid.MoveToFinished:Wait()
end
end