I have a script that has been troubling me for some time. Whenever NPCs spawn, they're supposed to get a checkpoint and move to that position. However, my script uses pathfinding. If it were simply a matter of using the MoveTo function once, it would be no problem. Here is my script:
wait(1)
npcs = game.Workspace.ActiveNPCs:GetChildren()
checkpoints = {Vector3.new(-99.2998886, 30.2999496, -91.5046234),
Vector3.new(-22.3003178, 30.2999496, -100.502426),
Vector3.new(47.6997795, 30.2999496, -100.501404),
Vector3.new(-18.2993164, 30.2999496, -48.5024147),
Vector3.new(-17.2979679, 30.3000755, 41.4907074),
Vector3.new(59.7020416, 30.3003025, 107.491859),
Vector3.new(60.7024612, 30.299818, 35.4920883),
Vector3.new(59.7007599, 30.2999249, -33.5009384),
Vector3.new(-19.2975655, 30.2995892, 115.490532),
Vector3.new(-118.297119, 30.2998695, 111.488739),
Vector3.new(-104.297592, 30.3003025, 29.4886169),
Vector3.new(-111.298828, 30.2999249, -19.5043755),
}
--[[local ray = Ray.new(nonPlayerChar.Torso.Position, nonPlayerChar.Torso.CFrame.lookVector*2)
local hit, position = game.Workspace:FindPartOnRay(ray, nonPlayerChar)
local distance1 = (position - nonPlayerChar.Torso.Position).magnitude--]]
wait(1)
function moveNPCs(v)
local checkpoint = checkpoints[math.random(1, #checkpoints)]
print(v.Name .. " will move to " .. tostring(checkpoint))
local path = game:GetService("PathfindingService"):ComputeRawPathAsync(v.Torso.Position, checkpoint, 100)
print(path.Status)
local points = path:GetPointCoordinates()
for _, point in pairs(points) do
v.Humanoid:MoveTo(point)
repeat
local distance = (point - v.Torso.Position).magnitude
if v.Humanoid.Sit == true then
v.Humanoid.Jump = true
end
if point.Y >= v.Torso.Position.Y + 1.5 then
v.Humanoid.Jump = true
end
local ray = Ray.new(v.Torso.Position, v.Torso.CFrame.lookVector*2)
local hit, position = game.Workspace:FindPartOnRay(ray, v)
local distance1 = (position - v.Torso.Position).magnitude
if hit ~= nil then
v.Humanoid.Jump = true
end
print(v.Name)
wait()
until distance < 3
end
wait()
print("test")
end
game.Workspace.ActiveNPCs.ChildAdded:connect(moveNPCs)
for _, npc in pairs(npcs) do
moveNPCs(npc)
end
The event causes each NPC to move at the same time, but their movements do not seem correct. The generic for loop generates the desired result from individual NPCs, however the NPCs do not move simultaneously. What can I do to make the function run on all NPCs at the same time, or at least make them move at the same time? Please, shed some light on me! Thanks in advance.
