How can i make the AI simply finds path easily im using SimplePath module and somehow i can see that if the player spawns it finds path but its little bit slower than you think if you have an idea help.
local SimplePath = require(script.Pathfinding)
local CharacterSize = script.Parent:GetExtentsSize();
local myHum = script.Parent:FindFirstChildWhichIsA('Humanoid')
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 10000
local temp = nil
local human = nil
local temp2 = nil
local player = false
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) then
if game.Players:GetPlayerFromCharacter(temp2) and (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
function checkSight(target)
local ray = Ray.new(script.Parent.HumanoidRootPart.Position, (target.Position - script.Parent.HumanoidRootPart.Position).Unit * 200)
local hit,position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent})
if hit then
if hit:IsDescendantOf(target.Parent) then
return true
end
end
return false
end
function checkHeight(target)
if math.abs(script.Parent.HumanoidRootPart.Position.Y - target.Position.Y) < 10.5 then
return true
end
return false
end
function checkDirect(target)
if checkSight(target) and checkHeight(target) and (script.Parent.HumanoidRootPart.Position - target.Position).Magnitude < 99999999999 then
return true
end
return false
end
local Dummy = script.Parent
local Goal = Vector3.new()
local Path = SimplePath.new(Dummy, {
AgentRadius = (CharacterSize.X+CharacterSize.Z)/4,
AgentHeight = CharacterSize.Y,
WaypointSpacing = math.huge,
})
Path.Visualize = true
Path.Blocked:Connect(function()
Path:Run(Goal)
end)
Path.WaypointReached:Connect(function()
Path:Run(Goal)
end)
Path.Error:Connect(function(errorType)
Path:Run(Goal)
end)
coroutine.wrap(function()
game:GetService("RunService").Stepped:Connect(function()
local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
if target then
if checkDirect(target) then
myHum:MoveTo(target.Position)
Path:Stop()
Goal = nil
elseif checkSight(target) and math.abs(script.Parent.HumanoidRootPart.Position.X - target.Position.X) < 1 and
math.abs(script.Parent.HumanoidRootPart.Position.Z - target.Position.Z) < 1 then
else
Goal = target.Position
Path:Run(Goal)
end
end
end)
coroutine.yield()
end)()