--------- Slim AI Script (don't edit unless you know what you're doing) -----------

local slime = script.Parent
local walkAnimation = slime.Slime:LoadAnimation(slime.Slime.Animation)

walkAnimation:Play()

slime.Slime.Died:Connect(function()
	slime:Destroy()
	-- TODO: Add fancier death or give rewards
end)

local hasDamagedRecently = false
local function damageIfHumanoidDebounced(part) 
	if not hasDamagedRecently then
		local humanoid = part.Parent:FindFirstChild("Humanoid")
		if humanoid then
			humanoid.Health -= damage
			hasDamagedRecently = true
			wait(damageDebounceDelay)
			hasDamagedRecently = false
		end	
	end
end
for _,part in pairs(slime:GetChildren()) do
	if part:IsA("BasePart") and part.Name ~= "HitBox"  then
		part.Touched:Connect(damageIfHumanoidDebounced)
	end
end

local function getClosestPlayer(position) 
	local closestPlayer = false
	local closestDistance = 999999999
	for _,player in pairs(game.Players:GetChildren()) do
		local playerPosition = game.Workspace:WaitForChild(player.Name).HumanoidRootPart.Position
		local dist = (position - playerPosition).magnitude
		if(dist < closestDistance) then
			closestDistance = dist
			closestPlayer = game.Workspace:WaitForChild(player.Name)
		end
	end
	return closestPlayer
end

local isWandering = false
while true do -- main AI loop
	wait(.1)
	local player = getClosestPlayer(slime.Head.Position)
	if player then
		local distance = (player.PrimaryPart.Position - slime.HumanoidRootPart.Position).magnitude
		if distance < detectionDistance then
			isWandering = false
			slime.Slime.WalkSpeed = chaseSpeed
			slime.Slime:MoveTo(player.PrimaryPart.Position)
		else
			if not isWandering then
				isWandering = true
				slime.Slime.WalkSpeed = wanderSpeed
				slime.Slime:MoveTo(slime.HumanoidRootPart.Position + Vector3.new(math.random(-wanderDistance, wanderDistance), 0, math.random(-wanderDistance, wanderDistance)))
				slime.Slime.MoveToFinished:Connect(function()
					isWandering = false
				end)
			end
		end		
	end
end




