local maxDistance = 20
local proximityLimit = 3
local updateInterval = 1
local rs = game:GetService("ReplicatedStorage")
local nearenemy = rs:WaitForChild("NearEnemy")
local sound = script.Parent.HumanoidRootPart:WaitForChild("Sound")
local hum = script.Parent:WaitForChild("Humanoid")
local lastUpdateTime = tick()
local randomTarget = nil
function FindTarget()
local target = nil
if not randomTarget or tick() - lastUpdateTime >= updateInterval then
local randomX = math.random(-maxDistance, maxDistance)
local randomZ = math.random(-maxDistance, maxDistance)
randomTarget = script.Parent.HumanoidRootPart.Position + Vector3.new(randomX, 0, randomZ)
lastUpdateTime = tick()
end
for _, player in ipairs(game.Players:GetPlayers()) do
local character = player.Character
if character and character:FindFirstChild("HumanoidRootPart") then
local distance = (character.HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).magnitude
if distance <= maxDistance then
target = character.HumanoidRootPart
break
end
end
end
return target or randomTarget
end
function bool(val)
if val == true then
nearenemy.Value = true
elseif val == false then
nearenemy.Value = false
end
end
game:GetService("RunService").Heartbeat:Connect(function()
local target = FindTarget()
if target then
if typeof(target) == "Vector3" then
script.Parent.Humanoid:MoveTo(target)
else
local direction = (target.Position - script.Parent.HumanoidRootPart.Position).unit
local distance = (target.Position - script.Parent.HumanoidRootPart.Position).magnitude
if distance <= maxDistance then
bool(true)
end
if distance > proximityLimit then
script.Parent.Humanoid:MoveTo(script.Parent.HumanoidRootPart.Position + direction * (distance - proximityLimit))
end
end
else
bool(false)
end
end)
sound:Play()
-- Debugging Prints
nearenemy.Changed:Connect(function(value)
print("NearEnemy Value changed to: ", value)
end)
Ive tried alot of things to fix this like dubugging, I kinda think that the reason is runservice but even if it was I dont know a work around, Thank you! (also my game will be halted because of this so please reply quick!)