Menu
CoddyTech

Đi theo con đường

Bài học 3 trên 22 trong khóa học Trò chơi Roblox: phòng thủ tháp của Coddy.

Một Humanoid di chuyển bằng MoveTo, và sự kiện MoveToFinished của nó kích hoạt khi nó đến nơi. Nó dừng sau 8 giây và kích hoạt với false, vì vậy kẻ địch chậm trên một đoạn đường dài sẽ được lệnh di chuyển lại cho đến khi đến nơi:

repeat
	humanoid:MoveTo(points[4].Position)
until humanoid.MoveToFinished:Wait()

Đi hết cả đường đi mất thời gian, nên walkPath chạy trong luồng riêng bằng task.spawn(walkPath, enemy), còn spawnEnemy tiếp tục chạy và trả về.

challenge icon

Thử thách

Dễ

Cho Zombie đi dọc theo đường đi.

  1. Viết walkPath(enemy): với i = 2, #waypoints, lặp lại enemy.Humanoid:MoveTo(waypoints[i].Position) cho đến khi MoveToFinished:Wait() báo rằng Zombie đã đến nơi hoặc not enemy.Parent; trả về nếu Zombie đã biến mất.
  2. Trong spawnEnemy, thêm task.spawn(walkPath, enemy) trước return enemy.

Nhấn Chơi: Zombie đi dọc theo đường đến căn cứ màu xanh. Sau đó nhấn Kiểm tra.

Tự làm thử

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

local enemies = workspace.Enemies

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

-- Các điểm mốc theo thứ tự (được đặt tên 1, 2, 3...)
local waypoints = workspace.Path.Waypoints:GetChildren()
table.sort(waypoints, function(a, b)
	return tonumber(a.Name) < tonumber(b.Name)
end)

-- Mỗi người chơi đều có Money trên bảng xếp hạng
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)

-- Đặt bài học 3: Đi theo đường đi ở đây

-- Một kẻ địch mới ở cổng, đang đi theo đường đi
local function spawnEnemy(kind)
	local enemy = ServerStorage.Enemies[kind]:Clone()
	-- xuất hiện ngay phía trên điểm mốc đầu tiên
	enemy:PivotTo(waypoints[1].CFrame + Vector3.new(0, 5, 0))
	enemy.Parent = enemies
	return enemy
end

-- Hiện tại chỉ có một kẻ địch
spawnEnemy("Zombie")

Tất cả bài học trong Trò chơi Roblox: phòng thủ tháp

Tự luyện tập: Playground Roblox