Menu
CoddyTech

웨이브 카운터

Coddy의 Roblox 게임: 타워 디펜스 코스 레슨. 22개 중 19번째.

플레이어는 게임이 어떻게 진행되고 있는지 확인해야 합니다. 보유 금액, 기지의 체력, 그리고 웨이브를 말이죠. HUD에는 각각을 표시하는 레이블인 Money, Base, Wave가 있습니다.

서버는 클라이언트가 읽을 수 있도록 이미 세 가지 값을 모두 보관합니다. Money는 leaderstats에, BaseHealth는 workspace 속성에, 그리고 이제 웨이브 번호도 보관합니다. 클라이언트는 이 값들을 처음 한 번 그리고 값이 바뀔 때마다 표시합니다. IntValue의 Changed와 속성의 GetAttributeChangedSignal을 사용합니다.

workspace:GetAttributeChangedSignal("Wave"):Connect(showStatus)

서버가 속성을 설정하기 전에 클라이언트가 접속할 수 있으므로 대체값을 사용해 읽으세요. workspace:GetAttribute("Wave") or 0.

challenge icon

챌린지

어려움

돈, 기지 체력, 웨이브를 화면에 표시하세요.

  1. DefenseServer의 웨이브 루프에서 휴식 시간 전에 워크스페이스 속성 Wave를 i로 설정하세요.
  2. DefenseClient에서 showStatus()를 작성하세요. hud.Money, hud.Base, hud.Wave에 각각 Money: 200, Base: 20, Wave 1/5가 표시되도록 하세요.
  3. 한 번 호출하고, Money의 Changed 이벤트가 발생할 때와 BaseHealth 또는 Wave가 변경될 때도 호출하세요.

‘플레이’를 누르세요. 레이블에 돈, 기지 체력, 웨이브가 반영됩니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Debris = game:GetService("Debris")
local Settings = require(game.ReplicatedStorage.Settings)

local remotes = game.ReplicatedStorage.Remotes
local enemies = workspace.Enemies
local towers = workspace.Towers
local towerPad = {} -- 각 타워 -> 타워가 놓인 패드

print("The base can take " .. Settings.BaseHealth .. " hits")

-- 순서대로 정렬된 경유지들 (이름은 1, 2, 3...)
local waypoints = workspace.Path.Waypoints:GetChildren()
table.sort(waypoints, function(a, b)
	return tonumber(a.Name) < tonumber(b.Name)
end)

-- workspace의 속성으로 저장된 기지의 체력: 모든 클라이언트가 읽을 수 있음
workspace:SetAttribute("BaseHealth", Settings.BaseHealth)

-- 모든 플레이어가 리더보드에 Money를 받음
Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local money = Instance.new("IntValue")
	money.Name = "Money"
	money.Value = Settings.StartMoney
	money.Parent = leaderstats
end)

-- 적이 기지에 도달함
local function damageBase(amount)
	local health = math.max(0, workspace:GetAttribute("BaseHealth") - amount)
	workspace:SetAttribute("BaseHealth", health)
	print("Base: " .. health)
end

-- 적을 경로를 따라 이동시킨다. MoveTo는 8초가 지나면 포기하고 이를 알린다
-- (MoveToFinished가 false를 반환함). 따라서 느린 적은 도착할 때까지 다시 이동 명령을 받는다.
local function walkPath(enemy)
	local humanoid = enemy.Humanoid
	for i = 2, #waypoints do
		repeat
			humanoid:MoveTo(waypoints[i].Position)
		until humanoid.MoveToFinished:Wait() or not enemy.Parent
		if not enemy.Parent then
			return
		end
	end
	-- 기지에 도달함
	damageBase(Settings.Enemies[enemy.Name].Damage)
	enemy:Destroy()
end

-- 입구에서 나타나 경로를 따라 이동하는 새 적
local function spawnEnemy(kind)
	local enemy = ServerStorage.Enemies[kind]:Clone()
	-- 첫 번째 경유지 바로 위에 배치됨
	enemy:PivotTo(waypoints[1].CFrame + Vector3.new(0, 5, 0))
	local info = Settings.Enemies[kind]
	enemy.Humanoid.MaxHealth = info.Health
	enemy.Humanoid.Health = info.Health
	enemy.Humanoid.WalkSpeed = info.Speed
	enemy.Parent = enemies
	-- 체력 바가 체력에 따라 변함
	enemy.Humanoid.HealthChanged:Connect(function(health)
		enemy.HealthBar.Back.Fill.Size = UDim2.fromScale(health / enemy.Humanoid.MaxHealth, 1)
	end)
	enemy.Humanoid.Died:Connect(function()
		-- 모든 플레이어가 보상을 받음
		for _, player in Players:GetPlayers() do
			player.leaderstats.Money.Value += info.Reward
		end
		enemy:Destroy()
	end)
	task.spawn(walkPath, enemy)
	return enemy
end

-- 한 지점에서 사거리 안에 있는 가장 가까운 살아 있는 적, 없으면 nil
local function nearestEnemy(position, range)
	local best, bestDistance = nil, range
	for _, enemy in enemies:GetChildren() do
		local root = enemy:FindFirstChild("HumanoidRootPart")
		if root and enemy.Humanoid.Health > 0 then
			local distance = (root.Position - position).Magnitude
			if distance <= bestDistance then
				best, bestDistance = enemy, distance
			end
		end
	end
	return best
end

-- 타워에서 목표물까지 뻗는 빛의 섬광
local function beam(from, to)
	local ray = Instance.new("Part")
	ray.Anchored = true
	ray.CanCollide = false
	ray.CanTouch = false
	ray.Material = Enum.Material.Neon
	ray.Color = Color3.fromRGB(255, 240, 150)
	ray.Size = Vector3.new(0.2, 0.2, (to - from).Magnitude)
	ray.CFrame = CFrame.lookAt((from + to) / 2, to)
	ray.Parent = workspace
	Debris:AddItem(ray, 0.1)
end

-- Frost: 적이 2초 동안 원래 속도의 일부로 이동함
local function slow(enemy, factor)
	if enemy:GetAttribute("Slowed") then
		return
	end
	enemy:SetAttribute("Slowed", true)
	local speed = Settings.Enemies[enemy.Name].Speed
	enemy.Humanoid.WalkSpeed = speed * factor
	task.delay(2, function()
		if enemy.Parent then
			enemy.Humanoid.WalkSpeed = speed
			enemy:SetAttribute("Slowed", nil)
		end
	end)
end

-- 발사: 목표물에 피해를 줌(Cannon이라면 주변의 모든 적에게도 피해를 줌)
local function shoot(tower, target, info)
	local damage = info.Damage * tower:GetAttribute("Level")
	local at = target.HumanoidRootPart.Position
	if info.Splash then
		for _, enemy in enemies:GetChildren() do
			local root = enemy:FindFirstChild("HumanoidRootPart")
			if root and (root.Position - at).Magnitude <= info.Splash then
				enemy.Humanoid:TakeDamage(damage)
			end
		end
	else
		target.Humanoid:TakeDamage(damage)
	end
	if info.Slow and target.Parent then
		slow(target, info.Slow)
	end
	beam(tower.Head.Position, at)
end

-- 타워의 동작: 사거리 안의 가장 가까운 적을 조준하고 발사한 뒤 재사용 대기시간만큼 기다림
local function runTower(tower)
	local info = Settings.Towers[tower.Name]
	while tower.Parent do
		local target = nearestEnemy(tower.Head.Position, info.Range)
		if target then
			tower.Head.CFrame = CFrame.lookAt(tower.Head.Position, target.HumanoidRootPart.Position)
			shoot(tower, target, info)
			task.wait(info.Cooldown)
		else
			task.wait(0.1)
		end
	end
end

-- 패드 위에 타워 건설
local function placeTower(pad, kind)
	local tower = ServerStorage.Towers[kind]:Clone()
	tower:PivotTo(pad.CFrame + Vector3.new(0, pad.Size.Y / 2 + 1, 0))
	tower:SetAttribute("Level", 1)
	tower.Parent = towers
	pad:SetAttribute("Used", true)
	towerPad[tower] = pad
	task.spawn(runTower, tower)
end

-- 클라이언트가 패드 위에 타워를 요청함. 모든 조건을 확인: 실제로 존재하고 비어 있는 패드,
-- 실제로 존재하는 타워, 그리고 구매에 필요한 돈.
remotes.Place.OnServerEvent:Connect(function(player, pad, kind)
	if typeof(pad) ~= "Instance" or pad.Parent ~= workspace.Pads or pad:GetAttribute("Used") then
		return
	end
	local info = typeof(kind) == "string" and Settings.Towers[kind]
	if not info then
		return
	end
	local money = player.leaderstats.Money
	if money.Value < info.Price then
		return
	end
	money.Value -= info.Price
	placeTower(pad, kind)
end)

-- 업그레이드: 다음 레벨의 비용은 매번 증가하고, 레벨이 오를 때마다
-- 타워의 공격력이 다시 추가됨
remotes.Upgrade.OnServerEvent:Connect(function(player, tower)
	if typeof(tower) ~= "Instance" or tower.Parent ~= towers then
		return
	end
	local level = tower:GetAttribute("Level")
	local cost = math.floor(Settings.Towers[tower.Name].Price * Settings.UpgradeCost * level)
	local money = player.leaderstats.Money
	if money.Value < cost then
		return
	end
	money.Value -= cost
	tower:SetAttribute("Level", level + 1)
end)

-- 판매: 가격의 절반을 돌려받고 패드는 다시 비게 됨
remotes.Sell.OnServerEvent:Connect(function(player, tower)
	if typeof(tower) ~= "Instance" or tower.Parent ~= towers then
		return
	end
	player.leaderstats.Money.Value += math.floor(Settings.Towers[tower.Name].Price / 2)
	towerPad[tower]:SetAttribute("Used", nil)
	towerPad[tower] = nil
	tower:Destroy()
end)

-- 한 웨이브: 적을 하나씩 내보낸 뒤 모두 사라질 때까지 기다림
local function runWave(list)
	for _, kind in list do
		spawnEnemy(kind)
		task.wait(Settings.SpawnGap)
	end
	while #enemies:GetChildren() > 0 do
		task.wait(0.2)
	end
end

-- 각 웨이브는 쉬는 시간이 지난 뒤 시작됨
for i, list in Settings.Waves do
	task.wait(Settings.WaveBreak)
	runWave(list)
end

Roblox 게임: 타워 디펜스의 모든 레슨

직접 연습해 보세요: Roblox 플레이그라운드