So I have an ai which chases players and pathfinds, it also has a function that checks if the player is in a clear line of sight and returns true or false, but whenever the ai loses sight of the player they make a path but the first waypoint is a little bit behind them. I tried to replace
humanoid:MoveTo(waypoint.Position)
with
humanoid:MoveTo(waypoints[3].Position)
That did the trick but made the npc stutter. Any help would be appreciated!
function pathfind(target)
local agentParams = {
['AgentHeight'] = 5,
['AgentRadius'] = 2,
['AgentCanJump'] = true,
Costs = {
Doors = 100
}
}
local path = pathfindingService:CreatePath(agentParams)
path:ComputeAsync(humanoidRootPart.Position, target.Position)
local waypoints = path:GetWaypoints()
if path.Status == Enum.PathStatus.Success then
for _, waypoint in ipairs(waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid.Jump = true
end
humanoid:MoveTo(waypoint.Position)
if checkSight(target) then
humanoidRootPart:SetNetworkOwner(game.Players:GetPlayerFromCharacter(target.Parent))
repeat
wait()
humanoid:MoveTo(target.Position)
if target == nil or target.Parent == nil or target.Parent.Humanoid == nil or target.Parent.Humanoid.Health < 1 or humanoid.Health < 1 then
break
end
until not checkSight(target)
humanoidRootPart:SetNetworkOwner(nil)
break
end
humanoid.MoveToFinished:Wait()
end
end
end
function checkSight(target)
local bots = {}
for i, v in pairs(game.Workspace:GetChildren()) do
if v:FindFirstChild('Pathfinding') then
table.insert(bots, v)
end
end
local ray = Ray.new(humanoidRootPart.Position, (target.Position - humanoidRootPart.Position).Unit * 9999999999999999)
local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent, table.unpack(bots)})
if hit then
if hit:IsDescendantOf(target.Parent) and math.abs(hit.Position.Y - humanoidRootPart.Position.Y) <= 8 then
return true
end
end
return false
end