--!strict
-- Script in ServerScriptService.
-- Target bots: a copy of ServerStorage.TargetBot stands on every part in Workspace.BotSpawns
-- (move / add / remove those parts to place them; each bot faces where its part faces).
-- They do nothing but stand and take bullets (SniperShots deals the damage to models tagged
-- "TargetBot"); a dead bot falls apart and a new one stands up on the same spot after RESPAWN_TIME.

local CollectionService = game:GetService("CollectionService")
local ServerStorage = game:GetService("ServerStorage")

local TAG = "TargetBot"
local RESPAWN_TIME = 4
local template = ServerStorage:WaitForChild("TargetBot") :: Model
local gameZone = workspace:WaitForChild("GameZone")
while gameZone:GetAttribute("Ready") ~= true do task.wait() end
local spawns = workspace:WaitForChild("BotSpawns")

local botsFolder = Instance.new("Folder")
botsFolder.Name = "TargetBots"
botsFolder.Parent = workspace

local function spawnBot(marker: BasePart)
	local bot = template:Clone()
	local root = bot:FindFirstChild("HumanoidRootPart") :: BasePart
	local humanoid = bot:FindFirstChildOfClass("Humanoid") :: Humanoid
	-- feet on the marker: the root sits half its height plus the hip height above the ground
	local lift = root.Size.Y / 2 + humanoid.HipHeight
	bot:PivotTo(marker.CFrame * CFrame.new(0, lift - marker.Size.Y / 2, 0))
	root.Anchored = true -- stands still, cannot be pushed over
	bot.Name = "Bot_" .. marker.Name
	CollectionService:AddTag(bot, TAG)
	bot.Parent = botsFolder
	humanoid.Died:Once(function()
		root.Anchored = false -- let the body fall
		task.delay(RESPAWN_TIME, function()
			bot:Destroy()
			if marker.Parent then
				spawnBot(marker)
			end
		end)
	end)
end

for _, marker in spawns:GetChildren() do
	if marker:IsA("BasePart") then
		spawnBot(marker)
	end
end

