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

for i,v in pairs(workspace:GetChildren()) do
    if v:FindFirstChild("HumanoidRootPart") then
        if v.HumanoidRootPart.Position.Magnitude <= 15 then
            local HRP = v.HumanoidRootPart
            local OHRP = script.Parent.HumanoidRootPart
            local human = script.Parent.Humanoid

            local path = game:GetService("PathfindingService"):FindPathAsync(OHRP,HRP)
            local points = path:GetWaypoints()

            if path.Status == Enum.PathStatus.Success then
                for i,v in pairs(points) do
                    human:MoveTo(v.Position)
                    human.MoveToFinished:Wait()
                    if v.Action == Enum.PathWaypointAction.Jump then
                        human.Jump = true
                    end
                end
            end
        else
            wait()
        end
    end
end

1 answer

Log in to vote
0
Answered by 4 years ago
Edited 4 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):

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:

for _, inst in pairs(workspace:GetChildren()) do
    if game.Players:GetPlayerFromCharacter(inst) then
        player = inst
        break
    end
end

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

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

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 — 4y
Ad

Answer this question