function:
function GetClosestPlayer(position) --Finds the closest player within a table of players
local cdist = 10000 --Closest distance so far
local closest = nil --Closest player
for _,v in pairs(game.Players:GetChildren()) do
if v.Character and v.Character.Humanoid.Health > 0 then
local dist = v:DistanceFromCharacter(position)
if dist < cdist then
cdist = dist
closest = v
end
end
end
return closest,cdist
end
使用例:
local target,dist = GetClosestPlayer() --target player to walk towards
if target then
target = target.Character
local torso = target:FindFirstChild("Torso")
if not torso then
torso = target:FindFirstChild("HumanoidRootPart")
end
if not torso then
return
end
if dist <= 80 then --walks at a normal speed towards player
Golem.Humanoid.WalkSpeed = stats["DefaultWalkSpeed"].Value
Golem.Humanoid:MoveTo(torso.Position,torso)
Golem.RightLeg.Foot.Stomp.Volume = 0.2
Golem.LeftLeg.Foot.Stomp.Volume = 0.2
speed = 1.4
else --sprints towards the player as fast as possible
Golem.Humanoid:MoveTo(torso.Position,torso)
Golem.RightLeg.Foot.Stomp.Volume = 0.5
Golem.LeftLeg.Foot.Stomp.Volume = 0.5
speed = 2.2
Golem.Humanoid.WalkSpeed = stats["RunSpeed"].Value
end