Hello everyone. I am new to scripting and I am trying to wrap my head around it. The code I have is compiled from tutorials, opensource codes, devforum, etc. for learning purposes, so bare with me if its really bad…
- What do you want to achieve?
I want to be able to click on a gui so that multiple NPCs within a given distance (say 10 magnitude) will follow the player. Anything beyond 20 studs will disconnect the NPC(s) and will stop following.
-
What is the issue?
There are multiple NPCs arbitrarily spawned in workspace and when I click on the ‘call’ button, only one random NPC will follow.
- What solutions have you tried so far?
I’ve tried looking for solutions on developer hub, but I am having trouble finding anything.
This is what was used to spawn arbitrarily positioned NPCs into workspace:
local PhysicsService = game:GetService("PhysicsService")
PhysicsService:RegisterCollisionGroup("Sheep")
PhysicsService:CollisionGroupSetCollidable("Sheep", "Sheep", false)
local sheep = game.ServerStorage.sheep
for _, part in pairs(sheep:GetDescendants()) do
if part:IsA("BasePart") then
part.CollisionGroup = "Sheep"
end
end
-- Clone sheep into workspace
for i=1, 10 do
local z = sheep:Clone()
z.Parent = game.Workspace
z:SetPrimaryPartCFrame(CFrame.new(Vector3.new(math.random(-50,50),5,math.random(-50,50))))
end
This is for the NPCs to follow:
-- Services
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local PathfindingService = game:GetService("PathfindingService")
local ServerStorage = game:GetService("ServerStorage")
local WorkSpace = game:GetService("Workspace")
-- Variables
local NPC = WorkSpace.sheep
local NPCHumanoid = WorkSpace.sheep.Humanoid
local NPCHumanoidRoot = WorkSpace.sheep.HumanoidRootPart
local Player = script.Parent -- StartPlayer.StarterCharacterScript is the player already
local PlayerHumanoidRoot = Player.HumanoidRootPart
local fireEvent = game.ReplicatedStorage.AIEvent.OnServerEvent
-- Setting up
NPC.Parent = workspace
NPC.PrimaryPart:SetNetworkOwner(nil)
-- Function
local function FollowPlayer()
local Path = PathfindingService:CreatePath()
local MovingToPosition = PlayerHumanoidRoot.Position - Vector3.new(5, 0, 0)
local ComputedPath = Path:ComputeAsync(NPC.HumanoidRootPart.Position, MovingToPosition)
return Path
end
-- Event variables
local Stepped
local Distance = (PlayerHumanoidRoot.Position.Magnitude - NPCHumanoidRoot.Position.Magnitude)
-- Movement
fireEvent:Connect(function()
if Distance < 10 then
Stepped = RunService.Stepped:Connect(function()
FollowPlayer()
local Path = FollowPlayer()
for _, waypoint in pairs(Path:GetWaypoints()) do
NPCHumanoid:MoveTo(waypoint.Position)
end
-- If distance is large then AI stop following--
if (PlayerHumanoidRoot.Position.Magnitude - NPCHumanoidRoot.Position.Magnitude) > 20 then
Stepped:Disconnect()
end
end)
end
end)
if fireEvent:Connect() then
print("Event connected")
end
Any feedback and help is welcomed. Afterall I am still learning.