山を崩そう
Coddyの「Robloxゲーム:ペットシミュレーター」コースのレッスン 3/18。
プレイヤーは山をクリックして壊します。パーツの中にある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内で、pileにClickDetectorを追加し、そのMouseClickをhitPile(player, pile)に接続します。spawnPileの下に、function hitPile(player, pile)を書きます。Health属性を1減らし、まだ0より大きければその値を保存して終了します。そうでなければ、pileのValueをプレイヤーのCoinsに加算し、pileを破棄します。
Playを押して、pileを3回クリックします。その後、Checkを押します。
自分で試してみよう
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
-- Meadow のすべてのスポットに山を配置する
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
spawnPile(spot)
end
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。