업그레이드
Coddy의 Roblox 게임: 타워 디펜스 코스 레슨. 18개 중 11번째.
타워는 레벨이 오르면 더 강해집니다. 레벨은 타워 모델의 Level 속성으로, 1부터 시작합니다. 레벨이 오를 때마다 타워의 대미지가 다시 더해지므로, 레벨 3 궁수는 12의 피해를 줍니다.
각 업그레이드 비용은 이전보다 더 비쌉니다. 타워 가격의 일부인 Settings.UpgradeCost에 현재 레벨을 곱합니다. math.floor는 결과를 정수로 만듭니다.
local cost = math.floor(Settings.Towers[tower.Name].Price * Settings.UpgradeCost * level)클라이언트에서 타워를 클릭하면 HUD의 Panel이 열리고 타워 이름, 레벨, 다음 업그레이드 가격이 표시됩니다. 클릭은 타워의 파트 중 하나에 닿으므로 target:FindFirstAncestorOfClass("Model")로 해당 파트가 속한 타워를 찾습니다. 패널에는 서버가 결정한 레벨이 표시됩니다. 타워의 Level 속성을 감시하고 값이 바뀌면 다시 그립니다.
챌린지
중급DefenseServer에서:
placeTower에서 타워의Level특성을 1로 설정합니다.shoot에서 피해량은info.Damage * tower:GetAttribute("Level")입니다.remotes.Upgrade.OnServerEvent(player, tower)를 연결합니다.towers에 속한 Instance가 아닌 것은 모두 거부하고, 비용을 계산한 뒤, 돈이 부족하면 요청을 거부하고, 돈을 차감한 다음 레벨을 1 올립니다.
DefenseClient에서: showPanel()(제목 Archer level 1, 버튼 Upgrade $45, 패널 표시, 아무것도 선택하지 않았을 때는 숨김)과 choose(tower)를 작성합니다. 타워를 클릭하면 해당 타워를 선택하고, 패널의 Upgrade 버튼은 해당 타워와 함께 remotes.Upgrade를 실행합니다.
Play를 누른 다음 Check를 누릅니다.
직접 해보기
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
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)
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.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
-- 발사: 대상에게 피해를 준다
local function shoot(tower, target, info)
local damage = info.Damage
local at = target.HumanoidRootPart.Position
target.Humanoid:TakeDamage(damage)
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.Parent = towers
pad:SetAttribute("Used", true)
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)
-- 한 웨이브: 적들을 하나씩 생성한 다음 모두 사라질 때까지 기다린다
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
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.