Hi!
I wanna make an NPC that runs away from a nearest player.
So my code isn’t working, cause I don’t know how to make that
Current Code:
function checkTorso()
local torso
for _,v in pairs(workspace:GetChildren()) do
if v:FindFirstChild("Humanoid") and v.Name ~= script.Parent.Name then
local temp = v:FindFirstChild("Torso")
if (script.Parent.Torso.Position - temp.Position).Magnitude < 30 then
torso = temp
end
end
end
return torso
end
while wait() do
local torso = checkTorso()
if torso then
script.Parent.Humanoid:MoveTo(Vector3.new(torso.CFrame.LookVector * -25, 0, torso.CFrame.LookVector * -25))
end
end
I’d recommend just looping through GetPlayers instead of having to find the players.
You’ll also need to use HumanoidRootPart instead, as R15 has UpperTorso but both R6 and R15 have a HRP.
function checkHRP()
local closest
local closestMagnitude = 30
for _, player in pairs(game:GetService("Players"):GetPlayers()) do
if player.Character then
local hrp = player.Character:FindFirstChild("HumanoidRootPart")
local hrpMagnitude = hrp and (script.Parent.Torso.Position - hrp.Position).Magnitude or math.huge
if closestMagnitude >= hrpMagnitude then
closestMagnitude = hrpMagnitude
closest = hrp
end
end
end
return closest
end
--now you can loop and run away if it finds one
local runAwayDistance = 10
function checkHRP()
local closest
local closestMagnitude = 30
for _, player in pairs(game.Players:GetPlayers()) do
if player.Character then
local hrp = player.Character.LowerTorso
local hrpMagnitude = hrp and (script.Parent.LowerTorso.Position - hrp.Position).Magnitude or math.huge
if closestMagnitude >= hrpMagnitude then
closestMagnitude = hrpMagnitude
closest = hrp
end
end
end
return closest
end
while wait() do
local torso = checkHRP()
if torso then
script.Parent.Humanoid:MoveTo((CFrame.new(script.Parent.LowerTorso.Position,torso.Position) * CFrame.new(0,0,runAwayDistance)).p)
end
end
it’s not running from the nearest player because it only runs away from the player that is 30 studs away, so it doesn’t detect anything that’s over that.
Aight, so other people have helped you clean up your code, but here’s the run down of what you need to do:
You need to have code that gets every player model in the game. After this, it loops through the list of player models, getting the distance from each player to the NPC. Now you know the closest player, so simply have it run away from their lookvector.
Code sample:
local ClosestPlayer
for i,v in pairs(PlayerList) do
local Distance = (NPC.HumanoidRootPart.Position-v.HumanoidRootPart.Position).magnitude
if ClosestPlayer then
if (ClosestPlayer.HumanoidRootPart.Position-v.HumanoidRootPart.Position).magnitude > Distance then
ClosestPlayer = v
end
else
ClosestPlayer = v
end
end
I get the confusion, but if you look at the script he provided as “Current Code”, it clearly says that if the player is closer than 30 units, then return that players torso.