Heya there.
I’m working on a pathfinding module for my game and as the title says, it’s stuttering for whatever reason.
--[[SERVICES]]--
local Players = game:GetService("Players")
local PathfindingService = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
--[[MODULE]]--
local PathfindingModule = {}
function PathfindingModule.Pathfind(NPC, AggroRange)
--//Preperation Variables
local Rootpart = NPC.PrimaryPart
local Humanoid = NPC:FindFirstChildWhichIsA("Humanoid")
local CharacterSize = NPC:GetExtentsSize()
local Objective = workspace:WaitForChild("Crystal")
Rootpart:SetNetworkOwner(nil)
--//PathfindingAgents
local PathfindingAgents = {
AgentRadius = (CharacterSize.X + CharacterSize.Z)/4,
AgentHeight = CharacterSize.Y,
AgentCanJump = true
}
local function FollowPath(Destination)
local Path = PathfindingService:CreatePath(PathfindingAgents)
Path:ComputeAsync(Rootpart.Position, Destination)
if Path.Status == Enum.PathStatus.Success then
local Waypoints = Path:GetWaypoints()
local Markers = {}
for _, Waypoint in pairs(Waypoints) do
if Waypoint.Action == Enum.PathWaypointAction.Jump then
Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
Humanoid:MoveTo(Waypoint.Position)
Humanoid.MoveToFinished:Wait(2)
end
for _, Maker in pairs(Markers) do
Maker:Destroy()
end
else
warn("NPC got stupid and forgot how to pathfind, sorry!")
end
end
local function FindNearestPlayer()
local NearestPlayer = nil
local ClosestDistance = AggroRange
local PlayerList = Players:GetPlayers()
for _, Player in pairs(PlayerList) do
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:FindFirstChildWhichIsA("Humanoid")
if Character and Humanoid.Health > 1 then
local Distance = (Character.PrimaryPart.Position - Rootpart.Position).Magnitude
if Distance < ClosestDistance then
ClosestDistance = Distance
NearestPlayer = Character
end
end
end
return NearestPlayer
end
RunService.Heartbeat:Connect(function()
local Target = FindNearestPlayer()
if Target then
Objective = Target
else
Objective = workspace:FindFirstChild("Crystal")
end
if Objective and Objective.PrimaryPart then
FollowPath(Objective.PrimaryPart.Position)
end
end)
end
return PathfindingModule