Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to make something target the nearest player?

Asked by 5 years ago

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:

01for 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
View all 24 lines...

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

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):

1local 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:

1for _, inst in pairs(workspace:GetChildren()) do
2    if game.Players:GetPlayerFromCharacter(inst) then
3        player = inst
4        break
5    end
6end

Then, in your magnitude loop, you should compare the distance between the player and the object:

1if (player.HumanoidRootPart.Position - v.HumanoidRootPart.Position).Magnitude <= 15 then
2    -- Do other stuff
3end

Doing just v.HumanoidRootPart.Position will not make it follow the player like you'd want it to.

0
Thanks! WIll try it later! AcrylixDev 119 — 5y
Ad

Answer this question