I tried to make a script that makes an npc chase the closest character, but the npc doesn’t move at all, and I have no idea how to fix it
my code:
local pathfind = game:GetService("PathfindingService")
local monster = script.Parent.PrimaryPart
local monster_model = script.Parent
local monsterPosition = monster.Position
local player = game:GetService("Players").PlayerAdded:Wait()
local loaded = player:HasAppearanceLoaded()
local players = game:GetService("Players")
monster:SetNetworkOwner(nil)
local function FindClosestPlayer()
local range = 100
local closest_character = nil
if loaded then
local character = player.Character
local character_position = character:FindFirstChild("HumanoidRootPart").Position
local distance_from_monster = (monsterPosition - character_position).Magnitude
if distance_from_monster <= range then
range = distance_from_monster
closest_character = character
end
end
task.wait()
return closest_character
end
local function GetPath(destination)
local path = pathfind:CreatePath({
AgentHeight = 13.36,
AgentRadius = 2.3,
AgentCanJump = false,
Costs = {
Water = math.huge,
Neon = math.huge
}
})
path:ComputeAsync(monsterPosition, destination)
return path
end
local function PathFindTo(destination)
local path = GetPath(destination)
local closest_player = FindClosestPlayer()
if closest_player and closest_player:FindFirstChildOfClass("Humanoid").Health > 0 then
for _, waypoint in pairs(path:GetWaypoints()) do
monster_model.Humanoid:MoveTo(waypoint.Position)
monster_model.Humanoid.MoveToFinished:Wait()
end
end
end
monster.Touched:Connect(function(hit)
if players:GetPlayerFromCharacter(hit.Parent) then
hit.Parent:FindFirstChildOfClass("Humanoid"):TakeDamage(math.huge)
end
end)
while monster_model do
local closest_player = FindClosestPlayer()
if closest_player then
PathFindTo(closest_player.PrimaryPart.Position + (closest_player.PrimaryPart.AssemblyLinearVelocity.Unit * 7))
task.wait(0.1)
end
end