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

How would I go about making my follow script detect the model closest to them?

Asked by
niroqeo 123
4 years ago

The title explains my problem.

if string.find(script.Parent.Name, "Blue") then
    EnemyTeam = "Red"
else
    EnemyTeam = "Blue"
end

function findTarget()
    for _, v in pairs(game.Workspace:GetChildren()) do
        if v:IsA("Model") and string.find(v.Name, EnemyTeam) and v:FindFirstChild("Humanoid") and v ~= script.Parent and v.Humanoid.Health > 0 and not game.Players:GetPlayerFromCharacter(v.Parent) then
            script.Parent.Humanoid:MoveTo(v.Torso.Position)
        end
    end
end

while true do
    wait(.2)
    findTarget()
end

1 answer

Log in to vote
1
Answered by
ArtBlart 533 Moderation Voter
4 years ago

You can use Magnitude to find the distance between 2 Vector3 points. The easiest way to do so is like so:

(Part1.Position - Part2.Position).Magnitude

My suggestion is to create a function that loops through every model, and compares the position of the model's primarypart to your humanoidrootpart, and once it finds the thing that's closest it returns it.

0
Thanks! niroqeo 123 — 4y
Ad

Answer this question