Menu
CoddyTech

山が戻ってくる

Coddyの「Robloxゲーム:ペットシミュレーター」コースのレッスン 4/20。

すべての山が壊れると、ゲーム内のコインがなくなります。壊れた山は、Settings.RespawnTime 秒後に元の場所に戻るようにします。

山は元の場所を覚えておく必要があります。山をキーにしたテーブルを使うと実現できます。

local pileSpot = {} -- 各pile -> そのpileが置かれているspot
pileSpot[pile] = spot

task.delay(seconds, fn, ...) は、今行っている処理を止めずに、引数を渡して後から関数を呼び出します。

task.delay(Settings.RespawnTime, spawnPile, spot)

テーブルにこれまで存在したすべての山が残り続けないように、山が壊れたときにテーブルから取り除きます。

challenge icon

チャレンジ

簡単

壊れた山を元の場所に自動で復活させます。

  1. 上の方で、local pileSpot = {}。
  2. spawnPileの中で、pileSpot[pile] = spotを保存します。
  3. 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回叩くと山の体力が 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:山の復活処理をここに追加する
	pile:Destroy()
end

-- Meadow の各スポットに山を置く
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
	spawnPile(spot)
end

Robloxゲーム:ペットシミュレーターのすべてのレッスン

自分で練習してみよう: Robloxプレイグラウンド