Menu
CoddyTech

山が戻ってくる

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

すべての山が壊れると、ゲーム内のコインがなくなります。壊れた山は、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から削除し、山を破棄して、task.delay(Settings.RespawnTime, spawnPile, spot)を実行します。

このレッスンの山は1秒後に戻ってきます。Playを押してから、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)

-- 山のクリック処理には、spawnPileの下で定義するhitPileが必要なので、
-- 両方より前のここで宣言する
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")
	pile:Destroy()
end

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

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

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