local parent = script.Parent
local humanoid = parent:WaitForChild("Humanoid")
local rootPart = parent:WaitForChild("HumanoidRootPart")
local TweenService = game:GetService("TweenService")
local VISION_RANGE = 20
local WALK_SPEED = 16
local isChasing = false
humanoid.WalkSpeed = WALK_SPEED
if parent:FindFirstChild("Anchored") then parent.Anchored = false end
function smoothLookAt(targetPos)
local direction = (targetPos - rootPart.Position).Unit
local goalCF = CFrame.new(rootPart.Position, rootPart.Position + direction * Vector3.new(1, 0, 1))
local tween = TweenService:Create(rootPart, TweenInfo.new(0.3), {CFrame = goalCF})
tween:Play()
end
function hasChildInRange()
for _, child in ipairs(workspace:GetChildren()) do
if child.Name == "Children" and child:FindFirstChild("HumanoidRootPart") then
local distance = (child.HumanoidRootPart.Position - rootPart.Position).Magnitude
if distance <= VISION_RANGE then
return true
end
end
end
return false
end
function findTarget()
if hasChildInRange() then return nil end
local closestPlayer = nil
local minDistance = 500
for _, player in ipairs(game.Players:GetPlayers()) do
local char = player.Character
if char and char:FindFirstChild("HumanoidRootPart") then
local distance = (char.HumanoidRootPart.Position - rootPart.Position).Magnitude
if distance < minDistance then
closestPlayer = char
minDistance = distance
end
end
end
return closestPlayer
end
while true do
task.wait(.2)
local target = findTarget()
if target then
isChasing = true
smoothLookAt(target.HumanoidRootPart.Position)
humanoid:MoveTo(target.HumanoidRootPart.Position)
if (target.HumanoidRootPart.Position - rootPart.Position).Magnitude < 5 then
print(parent.Name.." hit "..target.Name)
end
else
isChasing = false
local randomPos = rootPart.Position + Vector3.new(math.random(-10, 10), 0, math.random(-10, 10))
smoothLookAt(randomPos)
humanoid:MoveTo(randomPos)
task.wait(2)
end
end
Video with problem