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

How do I make a NPC follow the nearest player?

Asked by 3 years ago

So I am trying to make a game and need to have a cube follow and attack a player but I have tried too many times to count. Can anyone help me out?

0
try it yourself and then when you have some code come back and ask for help with your code CelticFury600 4 — 3y

1 answer

Log in to vote
0
Answered by 3 years ago

The following script provides the closest player once you input the origin. You can put this in a module script for easy access. Or a function, whatever works.

local players = game:GetService('Players')

function module.FindNearestPlayer (origin)
    -- so how this is going to work is it is going to cycle through
    -- all the players position
    -- once it finds the best one SO FAR it saves it to a variable.
    -- then it just keeps going comparing each position to the best one.
    -- then the best one is returned after everything is iterated.


    local bestChoice = nil 
    local bestPos = nil

    for i, player in pairs(players:GetPlayers()) do
        local char = player.Character or player.CharacterAdded:Wait()
        local pos = char.PrimaryPart.Position

        if bestChoice ~= nil then
            if (origin - pos).Magnitude < (origin - bestPos).Magnitude then
                bestChoice = player
                bestPos = pos
            end 
        else
            bestChoice = player
            bestPos = pos
        end
    end

    return bestChoice
end

Just call the module with the origin and you should get the nearest player.

The npc moving part you will have to do mostly yourself, this is because I have no clue how your game runs or works. But I assume you will do stuff with humanoid:MoveTo() so you can start there.

Ad

Answer this question