山を崩す
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に加算し、山を破棄します。
「プレイ」を押して山を3回クリックします。山が壊れ、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プレイグラウンド