Menu
CoddyTech

발사하기

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

적을 바라보게 하는 것은 작업의 절반입니다. shoot는 Humanoid:TakeDamage로 대상에게 피해를 주고, 머리에서 대상까지 짧은 빛의 섬광을 그립니다. 위에 붙여 넣을 준비가 된 섬광 코드입니다. runTower 위에 넣으세요. 얇은 네온 파트를 만들면 Debris가 0.1초 후에 제거합니다(맨 위에 local Debris = game:GetService("Debris")를 추가하세요).

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

발사 후 타워는 다시 발사할 수 있을 때까지 Cooldown만큼 기다립니다. 이것이 Archer는 빠르고 Cannon은 느린 이유입니다.

Humanoid의 체력이 0에 도달하면 Died 이벤트가 발생합니다. 쓰러진 적은 즉시 게임에서 사라져야 하므로, spawnEnemy는 Died를 적을 제거하는 동작에 연결합니다. 그러면 walkPath가 적이 사라진 것을 확인하고 멈춥니다.

challenge icon

챌린지

중급

타워가 발사하게 만드세요.

  1. 위에서 beam을 붙여 넣으세요. shoot(tower, target, info)를 작성하세요. 대상의 Humanoid에서 TakeDamage(info.Damage)를 호출한 다음, beam(tower.Head.Position, target.HumanoidRootPart.Position)를 호출하세요.
  2. runTower에서 방향을 돌린 다음 발사하고, info.Cooldown만큼 기다리세요. 대상이 없을 때는 0.1을 유지하세요.
  3. spawnEnemy에서 적의 Humanoid의 Died 이벤트가 발생하면 적을 제거하세요.

‘플레이’를 누르고 시작 지점 옆에 궁수를 배치하세요. 궁수가 좀비들에게 빛을 번쩍이며 쏘고, 좀비들이 쓰러집니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
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)
	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
	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

-- 레슨 10: 여기에 발사 기능을 구현

-- 타워의 동작: 범위 안에서 가장 가까운 적을 조준
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)
			task.wait(0.1)
		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
	task.spawn(runTower, tower)
end

-- 클라이언트가 패드 위에 타워를 건설해 달라고 요청한다
remotes.Place.OnServerEvent:Connect(function(player, pad, kind)
	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

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

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