How would I be able to get the player that is the closest to a part? (in this case humanoidrootpart)
I want to save the player as a variable, because I am planning on implementing it into the pathfinding script I am currently working on. I might also add a range, but that’s for another time. Please send some help as I cannot finish my script without this. I have looked through countless other posts, but none seem to work for me.
well, that is quite simple. If you look at the post I’ve provided above it shows how you can get the nearest player, and to get their position, you could do:
local nearestPlayerPos = player.Character.HumanoidRootPart.CFrame
or
local nearestPlayerPos = player.Character.HumanoidRootPart.Position
local Players = game:GetService("Players")
local function nearestPlayerToPart(part: BasePart): Player?
local nearestPlayer = nil
local nearestDistance = math.huge
for _, player in ipairs(Players:GetPlayers()) do
local character = player.Character
if character then
local rootPart = character.PrimaryPart
if rootPart then
local distance = (part.Position - rootPart.Position).Magnitude
if distance < nearestDistance then
nearestPlayer = player
nearestDistance = distance
end
end
end
end
return nearestPlayer
end
nearestPlayerToPart(Instance.new("Part", workspace))
local Players = game:GetService("Players")
local rs = game:GetService("ReplicatedStorage")
local forbidden = rs:WaitForChild("Forbidden")
local ai = require(forbidden:WaitForChild("AI"))
local NPC = script.Parent
local target = workspace.dest
wait(2)
ai.SmartPathfind(NPC,playerhere,true,{Visualize = true, Tracking = true})
this just uses an api from a youtube video, so theres not much to see.
‘ai.smartpathfind’ function is what bugs when i put it in a loop. and in playerhere is going to be the variable if possible.
Yes, because the nearest player is being returned from the function.
local nearestPlayer = nearestPlayerToPart(Instance.new("Part", workspace))
if nearestPlayer then
-- there might not even exist a nearest player.
-- make sure to validate it before doing anything.
end
local nearestPlayer = nearestPlayerToPart(NPC.HumanoidRootPart))
if nearestPlayer then
ai.SmartPathfind(NPC,nearestPlayer,true,{Visualize = true, Tracking = true})
end
(the parthfinding works perfectly without it being in a loop. but i think a loop is required to constantly get the closest player)
Looks fine to me. Since we want the pathfinding to be constant (running at all times), we do wrap it in a while loop:
while true do
local nearestPlayer = nearestPlayerToPart(NPC.HumanoidRootPart))
if nearestPlayer then
ai.SmartPathfind(
NPC,
nearestPlayer,
true,
{ Visualize = true, Tracking = true }
)
end
task.wait(0.1) -- you *might* want to add a cooldown for each look up.
end
Likely because the path is being recalculated a bunch of times a second. I’m fairly sure SimplePath optimizes this, though. So you might want to use that.