✓ Accepted answer
This is the thought process I would recommend following when you complete your scripting tasks:
What are you trying to achieve, and what tools are available to you to do this?
Well for starters, you have a MoveTo command, a magnitude calculator, and a list of players along with their characters and torso positions.
What could cause errors?
If someone's character, torso, or humanoid isn't present, this may cause an error, depending on what is needed.
Iterating through players seems like it will be necessary, so a "for" loop will most likely be used. You'll want to put this into another function so that it can be called for the MoveTo command.
I would recommend setting up two variables, one for which object is closest, and another value representing how close the closest object is. Each time the for loop looks through the characters, it should compare distances to determine if someone is closer than another.
When all of this information is put together, you'll come up with something like this.
local hum = game.Workspace:WaitForChild("Zombie"):WaitForChild("Humanoid")
function nearPersonPos(obj)
local closest = nil
local bestDist = nil
for _,v in pairs(game.Players:GetChildren()) do
if v.Character then
local tors = v.Character:FindFirstChild("Torso")
if tors then
local dist = (tors.Position-obj.Position).magnitude
if not bestDist or dist<bestDist then
closest = v
bestDist = dist
end
end
end
end
return closest
end
while hum and hum.Parent and hum.Parent:FindFirstChild("Torso") do
hum:MoveTo(nearPersonPos(obj) or hum.Parent.Torso.Position)
wait(1)
end
Keep in mind this will NOT pathfind for you. To do that, I would suggest looking into the other answer's wiki article link, or even look into some A* path-finding algorithms of your own; they can be very fun to use.
2 comments
Wow, this is a lot more complex that I thought it'd be! Thank you for such a detailed answer, its really helpful. Is a pathfinding algorithm required if I just want the NPC to go on a straight path towards the player? Also, do you have any recommendations of good LUA tutorials? I went through Dingdong272's tutorial places but I think I need some more practice. Thank you again for the help!
ROBLOX has a great tutorial series https://www.youtube.com/channel/UCjiPEaapiHbJMoAdi_L8fNA (although a lot of it is about building) and the wiki has a pretty good one too. As for pathfinding, it is not necessary if you only want your minions to walk in straight lines. However, if you want them to maneuver around terrain, it can prove very useful.