How come this script can attack whoever closet to it? can someone explain
local myHuman = script.Parent:WaitForChild("Humanoid")
local myRoot = script.Parent:WaitForChild("HumanoidRootPart")
local attackCool = true
local clone = script.Parent:Clone()
function checkDist(target)
return (myRoot.Position - target.Position).Magnitude
end
function getUnstuck()
myHuman:Move(Vector3.new(math.random(-1,1),0,math.random(-1,1)))
myHuman.Jump = true
wait(0.5)
end
function findTarget()
print("Hello")
local dist = 50
local target = nil
for i,v in ipairs(workspace:GetChildren()) do
local human = v:FindFirstChild("Humanoid")
local torso = v:FindFirstChild("Torso") or v:FindFirstChild("HumanoidRootPart")
if human and torso and v.Name ~= script.Parent.Name then
if checkDist(torso) < dist and human.Health > 0 then
target = torso
dist = checkDist(torso)
end
end
end
return target
end
function attack(target)
if attackCool == true then
attackCool = false
target.Parent.Humanoid:TakeDamage(10)
spawn(function() wait(0.5) attackCool = true end)
end
end
function main()
local target = findTarget()
if target then
if checkDist(target) > 6000 then
getUnstuck()
else
attack(target)
end
else
getUnstuck()
end
end
while wait() do
if myHuman.Health > 0 then
main()
else
break
end
end
function attack(target)
if attackCool == true then
attackCool = false
target.Parent.Humanoid:TakeDamage(100)
spawn(function() wait(0.5) attackCool = true end)
end
end