Hey! My AI code for a monster in my game isn’t working well.
My AI keeps walking into trees or inclines and getting stuck for 10-15 seconds when it tries to follow me in sometimes. I want this fixed so it will just follow my player without getting stuck.
I tried to make the AI not follow you if you’re not moving, but it results in the strange effect of the mob not chasing you, and the issue still persists.
I do this on the client because the entire engine I use renders terrain on the client so server sided pathfinding would not work as the mob would just fall right through the floor.
Any help would be appreciated. Thanks!
This is my code.
local Char = script.Char
Char.Parent = workspace
Char.PrimaryPart.Anchored = false
Char.PrimaryPart.CFrame = game.Players.LocalPlayer.Character.PrimaryPart.CFrame
local PFS = game.PathfindingService
function get()
local c
local dist = 999999
for _,i in pairs(game.Players:GetChildren()) do
local char = i.Character
if (char.PrimaryPart.Position - Char.PrimaryPart.Position).Magnitude < dist then
c = char
dist = (char.PrimaryPart.Position - Char.PrimaryPart.Position).Magnitude
end
end
return c
end
print("C")
repeat until get()
wait(1)
print("win")
local endpos = get().PrimaryPart.Position
local path = PFS:FindPathAsync(Char.PrimaryPart.Position,endpos)
local wps = path:getWaypoints()
function follow()
endpos = get().PrimaryPart.Position
if get().PrimaryPart.Velocity.Magnitude > 2 then
path = PFS:FindPathAsync(Char.PrimaryPart.Position,endpos)
if path.Status == Enum.PathStatus.Success then
wps = path:getWaypoints()
print("e")
else
print("x")
return follow()
end
local Waypoints = {}
for _,i in pairs(wps) do
Waypoints[#Waypoints+1] = {i.Position, i.Action}
if _ > 50-1 then
break
end
end
--print(Waypoints)
for _,i in pairs(Waypoints) do
Char.Humanoid:MoveTo(i[1])
if i[2].Name == "Jump" then
Char.Humanoid.Jump = true
end
Char.Humanoid.MoveToFinished:Wait()
end
follow()
else
repeat wait() until get().PrimaryPart.Velocity.Magnitude > 2
return follow()
end
end
follow()
The script runs in the Workspace with the RunContext as Client.