ive been trying to make an enemy ai for my game for couple of hours but just now i firgured out how to do it but its very delayed? Any idea?
1 Like
code
local char = script.Parent
local hum = char:WaitForChild("EnemyHumanoid")
local pathfindingserv = game:GetService("PathfindingService")
char.PrimaryPart:SetNetworkOwner(nil)
local function findtarget()
local players = game.Players:GetPlayers()
local maxdist = 100
local dist
local nearesttarget
for i, player in pairs(players) do
if player.Character then
local target = player.Character
dist = (char.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if dist < maxdist then
nearesttarget = target
maxdist = dist
end
end
end
return nearesttarget
end
local function getpath(destination)
local pathparams = {
["AgentHeight"] = 6,
["AgentRadius"] = 4,
["AgentCanJump"] = true
}
local path = pathfindingserv:CreatePath()
path:ComputeAsync(char.HumanoidRootPart.Position,destination.HumanoidRootPart.Position)
return path
end
local function walkto(destination)
local path = getpath(destination)
if path.Status == Enum.PathStatus.Success then
for i, waypoint in pairs(path:GetWaypoints()) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
hum:ChangeState(Enum.HumanoidStateType.Jumping)
end
hum:MoveTo(waypoint.Position)
hum.MoveToFinished:Wait()
end
end
end
while wait() do
local target = findtarget()
if target then
walkto(target)
end
end
1 Like
Could you elaborate by how they’re delayed?
Also I DO NOT recommend assigning a name to index in for
loops if you’re NOT gonna use it. This can cause memory leaks, therefore, a bad practice! Many programmers commit this mistake, and professionals are aware of it.
Instead, assign it with underscore, in other words, a dash (_).
1 Like
The pathfinding isnt really updating instantly so it leaves with an weird result of the enemy turning left and right
1 Like
im also very new to path finding
1 Like