Những chồng xu quay lại
Bài học 4 trên 20 trong khóa học Trò chơi Roblox: mô phỏng thú cưng của Coddy.
Khi tất cả các đống đều bị phá, trò chơi sẽ hết xu. Đống bị phá cần xuất hiện lại tại vị trí của nó sau Settings.RespawnTime giây.
Đống cần ghi nhớ vị trí của nó. Một bảng dùng đống làm khóa sẽ giúp làm việc đó:
local pileSpot = {} -- mỗi pile -> vị trí đặt pile đó
pileSpot[pile] = spottask.delay(seconds, fn, ...) gọi một hàm sau đó, kèm theo các đối số, mà không dừng bất cứ thứ gì ngay lúc này:
task.delay(Settings.RespawnTime, spawnPile, spot)Hãy xóa đống khỏi bảng khi nó bị phá để bảng không giữ lại mọi đống từng tồn tại.
Thử thách
DễĐưa một đống đã vỡ trở lại vị trí cũ của nó.
- Gần đầu tệp:
local pileSpot = {}. - Trong
spawnPile, lưupileSpot[pile] = spot. - Trong
hitPile, khi đống vỡ: lấy vị trí của nó, đặtpileSpot[pile] = nil, phá hủy đống, rồi gọitask.delay(Settings.RespawnTime, spawnPile, spot).
Nhấn Chơi rồi phá một đống: 3 giây sau, một đống mới sẽ xuất hiện ở vị trí cũ. 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 piles = workspace.Piles
print("A Meadow pile gives " .. Settings.PileValue .. " coins")
-- Mỗi người chơi có Coins 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 coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Parent = leaderstats
end)
-- Thao tác nhấp vào đống xu cần hàm hitPile, được viết sau spawnPile: khai báo tên hàm
-- ở đây, trước cả hai hàm
local hitPile
-- Một đống xu tại một vị trí: bản sao của ServerStorage.CoinPile, với lượng máu
-- và giá trị là các thuộc tính
local function spawnPile(spot)
local pile = ServerStorage.CoinPile:Clone()
pile.Position = spot.Position
pile:SetAttribute("MaxHealth", Settings.PileHealth)
pile:SetAttribute("Health", Settings.PileHealth)
pile:SetAttribute("Value", Settings.PileValue)
-- Nhấp vào đống xu để đánh nó
local detector = Instance.new("ClickDetector")
detector.Parent = pile
pile.Parent = piles
detector.MouseClick:Connect(function(player)
hitPile(player, pile)
end)
return pile
end
-- Mỗi lần đánh làm đống xu mất 1 máu;
-- khi máu về 0, đống xu vỡ và trao số xu bằng giá trị của nó
function hitPile(player, pile)
local health = pile:GetAttribute("Health") - 1
if health > 0 then
pile:SetAttribute("Health", health)
return
end
player.leaderstats.Coins.Value += pile:GetAttribute("Value")
-- Bài học 4: Đống xu xuất hiện trở lại sẽ nằm ở đây
pile:Destroy()
end
-- Mỗi vị trí trong Meadow có một đống xu
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
spawnPile(spot)
end
Tất cả bài học trong Trò chơi Roblox: mô phỏng thú cưng
Tự luyện tập: Playground Roblox