Hey everyone, I’m trying to make an enemy AI that attacks the closest player. How would I get the player’s character/humanoid from a server script in the enemy? Here’s the code I have so far to do this:
-- Variables --
local PathfindingService = game:GetService("PathfindingService")
local body = script.Parent:WaitForChild("Torso")
local hum = script.Parent:WaitForChild("Humanoid")
game.Players.PlayerAdded:Connect(function(plr)
local plrChar = plr.Character or plr.CharacterAdded:Wait()
local plrHum = plrChar:WaitForChild("Humanoid")
end)
-- Enemy AI --
local attackPath = PathfindingService:CreatePath()
attackPath:ComputeAsync(body.Position, plrHum.position)
Ok, first you need a function to get the closest player to a given enemy. Then you can just computeAsync:
local function getClosestPlayer(zombie)
local closest = math.huge
for _, plr in ipairs(game.Players:GetPlayers()) do
local distance = (zombie.Position - plr.Character.HumanoidRootPart.Position).Magnitude
if distance < closest then
closest = distance
end
end
end
-- Enemy AI --
while task.wait() do
local attackPath = PathfindingService:CreatePath()
attackPath:ComputeAsync(body.Position, getClosestPlayer(body))
end
I haven’t worked with pathfinding service, so I don’t know how well this will run.