ROBLOX Studio: How do I make this NPC follow the nearest player which is always different and not sometimes run into the wall? It looks like your post is mostly code; please add some more details.
local larm = script.Parent:FindFirstChild("HumanoidRootPart")
local rarm = script.Parent:FindFirstChild("HumanoidRootPart")
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = math.huge
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("HumanoidRootPart")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
while true do
wait(math.random(1,5))
local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
if target ~= nil then
script.Parent.Humanoid:MoveTo(target.Position, target)
end
end
First off, make sure on line 5 you have game.Workspace:GetChildren()
rather than game.Workspace:children()
Now in order to go about getting the closest player, you can create a table to store the distance of every player from your NPC: local playerDistances = {}
. Now you can use a while loop around all of your NPC movement code (so that the NPC continues to follow the player). Inside the if statement where you check for temp, human, and human.Health, you can add the distance of the players HumanoidRootPart (the part that stores a player's position) from the NPC by doing table.insert(playerDistances,(<Player HumanoidRootPart>.Position-<NPC HumanoidRootPart>.Position).magnitude)
You can then refresh the table of distances every time the loop goes around by doing table.clear(playerDistances)
right before the while loop's end
. This ensures there is no unnecessary old data in the table that will mess with your NPC.
You can then access the closest player by doing playerDistances[1]
Now in order to not have the NPC run into a wall, I would recommend using Roblox Lua's PathfindingService
. You can use :CreatePath(), :GetWaypoints(), :MoveTo(), and :MoveToFinished:Wait()
to continuously make sure the NPC calculates an open path and can reach the player. Here are some links to the Developer Wiki page on PathfindingService
:
https://developer.roblox.com/en-us/api-reference/class/PathfindingService
^^ All the functions, properties, etc.
https://developer.roblox.com/en-us/articles/Pathfinding
^^ How to use PathfindingService
note that you should also add the players HumanoidRootPart to the table as well since you cant make a path solely based on distance to do this just add another list with the same method stated above and append the player to this one instead of the distance.