硬币堆又回来了
Coddy Roblox 游戏:宠物模拟器 课程的第 4 课,共 20 课。
所有金币堆都被打碎后,游戏中就没有金币了。被打碎的金币堆应在 Settings.RespawnTime 秒后回到原来的位置。
金币堆需要记住自己的位置。用以金币堆为键的表就能做到这一点:
local pileSpot = {} -- 每个 pile 对应它所在的 spot
pileSpot[pile] = spottask.delay(seconds, fn, ...) 会在之后调用函数,并传入参数,不会中断当前的任何操作:
task.delay(Settings.RespawnTime, spawnPile, spot)金币堆被打碎时,要将它从表中移除,这样表就不会一直保存曾经存在过的所有金币堆。
挑战
简单让损坏的金币堆在原来的位置重新出现。
- 在靠近顶部的位置添加:
local pileSpot = {}。 - 在
spawnPile中,保存pileSpot[pile] = spot。 - 在
hitPile中,金币堆损坏时:读取它的位置,将pileSpot[pile] = nil,销毁金币堆,然后调用task.delay(Settings.RespawnTime, spawnPile, spot)。
按“开始”并打破一个金币堆:3 秒后,新的金币堆会出现在原来的位置。然后按“检查”。
亲手试试
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")
-- 每个玩家的排行榜上都有 Coins
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)
-- 点击钱堆时需要用到 hitPile,它写在 spawnPile 下方:先在
-- 这里声明它,再定义这两个函数
local hitPile
-- 每个位置上的钱堆都是 ServerStorage.CoinPile 的副本,其生命值
-- 和值都存为属性
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)
-- 点击钱堆即可击打它
local detector = Instance.new("ClickDetector")
detector.Parent = pile
pile.Parent = piles
detector.MouseClick:Connect(function(player)
hitPile(player, pile)
end)
return pile
end
-- 每击打一次,钱堆的生命值减少 1;
-- 生命值降到 0 时,钱堆会破碎,并按其值发放金币
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")
-- 第 4 课:Piles Come Back 的代码写在这里
pile:Destroy()
end
-- 在 Meadow 的每个位置放一个钱堆
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
spawnPile(spot)
end
Roblox 游戏:宠物模拟器中的所有课
自己练习: Roblox 在线编辑器