拆分一堆
Coddy Roblox 游戏:宠物模拟器 课程的第 3 课,共 20 课。
玩家点击石堆来打碎它。部件中的 ClickDetector 会在玩家足够靠近时,在服务器上触发 MouseClick,并传入点击的玩家。
每次点击都会使石堆的 Health 减少 1。当它变为 0 时,石堆就会碎裂:玩家会获得石堆对应的金币 Value,石堆也会被销毁。
local health = pile:GetAttribute("Health") - 1
if health > 0 then
pile:SetAttribute("Health", health)
return
end
-- 已损坏点击事件在 spawnPile 中连接,并会调用写在 spawnPile 下方的 hitPile。函数只能使用已声明的局部名称,所以要先在这两个函数上方声明 local hitPile,然后再用 function hitPile(player, pile) 填入函数内容。
挑战
简单点击堆来打破它。
- 在
spawnPile上方,声明local hitPile。 - 在
spawnPile中,给堆添加一个 ClickDetector;它的MouseClick会调用hitPile(player, pile)。 - 在下面,编写
function hitPile(player, pile):将Health减去 1;如果结果大于 0,就保存它并停止;否则,将堆的Value加到 Coins 上,并销毁这个堆。
按“开始”,然后点击一个堆三次:它会被打破,Coins 会增加 5。然后点击“检查”。
亲手试试
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)
-- 每个位置上的金币堆: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)
pile.Parent = piles
return pile
end
-- 第 3 课:在这里编写击碎金币堆的代码
-- Meadow 中的每个位置都有一个金币堆
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
spawnPile(spot)
end
Roblox 游戏:宠物模拟器中的所有课
自己练习: Roblox 在线编辑器