I tried to create something that targets the nearest player. I don't know how to target the nearest player, but I got the path finding thing down.
Here's what I've got so far:
01 | for i,v in pairs (workspace:GetChildren()) do |
02 | if v:FindFirstChild( "HumanoidRootPart" ) then |
03 | if v.HumanoidRootPart.Position.Magnitude < = 15 then |
04 | local HRP = v.HumanoidRootPart |
05 | local OHRP = script.Parent.HumanoidRootPart |
06 | local human = script.Parent.Humanoid |
07 |
08 | local path = game:GetService( "PathfindingService" ):FindPathAsync(OHRP,HRP) |
09 | local points = path:GetWaypoints() |
10 |
11 | if path.Status = = Enum.PathStatus.Success then |
12 | for i,v in pairs (points) do |
13 | human:MoveTo(v.Position) |
14 | human.MoveToFinished:Wait() |
15 | if v.Action = = Enum.PathWaypointAction.Jump then |
The function you'd want to use here is GetPlayerFromCharacter()
, which is called from the Players
service. If it finds a player associated with what you give it, it returns that player. Otherwise, the function returns nil.
What I suggest doing is to define an empty variable on the lowest scope (which would be before every loop and function in your script):
1 | local player -- This variable is currently nil, but will be assigned later |
Then, before you start your magnitude loop, use a loop like this to set player
to a valid player:
1 | for _, inst in pairs (workspace:GetChildren()) do |
2 | if game.Players:GetPlayerFromCharacter(inst) then |
3 | player = inst |
4 | break |
5 | end |
6 | end |
Then, in your magnitude loop, you should compare the distance between the player and the object:
1 | if (player.HumanoidRootPart.Position - v.HumanoidRootPart.Position).Magnitude < = 15 then |
2 | -- Do other stuff |
3 | end |
Doing just v.HumanoidRootPart.Position
will not make it follow the player like you'd want it to.