I am trying to make a Zombie for my game, that follows you using PathFindingService. Now, the script for the pathfinding works, but when the player moves, the zombie starts to lag (Watch the video to see what I mean) How can I fix this?
Note: The zombie lags ONLY when the player is moving. If the player stands still, the zombie does not lag.
Pathfinding script:
local PathFindingService = game:GetService("PathfindingService")
local ZombieHumanoid = script.Parent:WaitForChild("HumanoidZ")
local ZombieTorso = script.Parent:WaitForChild("Torso")
local Path = PathFindingService:CreatePath({
AgentRadius = 3,
AgentHeight = 5,
AgentCanJump = false,
AgentJumpHeight = 0,
AgentMaxSlope = 45,
AgentFallHeight = 10,
})
local PlayerLoadedEvent = script.Parent:WaitForChild("PlayerLoaded")
local Player
local function FollowPlayer()
while true do
Path:ComputeAsync(ZombieTorso.Position, Player.Position)
local OldHRP = Player.Position
local Waypoints = Path:GetWaypoints()
for i, Waypoint in pairs(Waypoints) do
ZombieHumanoid:MoveTo(Waypoint.Position)
ZombieHumanoid.MoveToFinished:Wait()
--Updates Waypoints if the player has moved--
if OldHRP ~= Player.Position then
break
end
end
wait()
end
end
-- gets the player's HumanoidRootPart --
PlayerLoadedEvent.Event:Connect(function(PlayerHRP)
Player = PlayerHRP
FollowPlayer()
end)