Hello, I’m trying to learn how to use pathfinding currently however I’ve run into a problem. I don’t know how to update pathfinding to find the nearest player.
I’ve attempted it myself, already but it either lags the game a lot or just goes backwards for a few second. And from what I’m aware there’s nothing in the documentations to help me.
Anyways here’s the script (Also it’s a module script to prevent lag with multiple zombies)
local PathfindingService = game:GetService("PathfindingService")
function Module.Summon(Zombie)
local MoveToPos = workspace.MoveToPart.Position --This is temporary
local Path = PathfindingService:CreatePath({
AgentCanJump = true,
AgentRadius = 3,
AgentHeight = 6,
})
local function FollowPlayer()
local succ, err = pcall(function()
Path:ComputeAsync(Zombie.HumanoidRootPart.Position, MoveToPos)
end)
if succ and Path.Status == Enum.PathStatus.Success then
for i, v in Path:GetWaypoints() do
local Pathway = Instance.new("Part") --Just to display the path
Pathway.Parent = workspace
Pathway.Anchored = true
Pathway.CanCollide = false
Pathway.Size = Vector3.new(1,1,1)
Pathway.Position = v.Position
Pathway.Transparency = 0.65
end
else
warn(err)
end
end
end
Try not to create functions in other functions. Doesn’t look nice though you can do it
function FindNearestPlayer()
local nearestplayer
local maxdistance = 10000
for _,plr in pairs(game.Players:GetPlayers()) do
local distance = (plr.Character.HumanoidRootPart.Position - Zombie.HumanoidRootPart.Position).Magnitude
if distance < maxdistance then
nearestplayer = plr
maxdistance = distance -- Shorten the distance so npc won't get distracted by further players
end
end
return nearestplayer
end
You can call this function in your followplayer function to get the nearest player
Hey, it works but I still need help with the zombie always following the player and not cause lag. As of now it just moves to the player’s location and then stops
try giving simplepath a try, im using it for my game that uses 50+ enemies and i get no lag from it
its also super easy to use:
--Import the module so you can start using it
local ServerStorage = game:GetService("ServerStorage")
local SimplePath = require(ServerStorage.SimplePath)
--Define npc
local Dummy = workspace.Dummy
-- Define a part called "Goal"
local Goal = workspace.Goal
--Create a new Path using the Dummy
local Path = SimplePath.new(Dummy)
--Helps to visualize the path
Path.Visualize = true
while true do
Path:Run(Goal)
end