クリックして壊そう
Coddyの「Robloxゲーム:ペットシミュレーター」コースのレッスン 6/18。
ボタンにはClickDetectorで問題ありませんが、ほとんどのシミュレーターではクライアント上でクリックを読み取るため、サーバーが応答する前にクリックした瞬間にゲームが反応できます(音や揺れなど)。クライアントのマウスは、何をクリックしたかを把握しています:
local mouse = me:GetMouse()
mouse.Button1Down:Connect(function()
print(mouse.Target) -- クリックした位置にあるパーツ、または nil
end)クライアントだけでは山を壊せません。山とコインはサーバーが管理しています。クライアントとサーバー間のメッセージ用に作られたオブジェクトであるRemoteEventを通じて、サーバーに要求を送ります:
-- クライアント
remotes.Hit:FireServer(pile)
-- サーバー: Roblox は送信元のプレイヤーを最初に追加する
remotes.Hit.OnServerEvent:Connect(function(player, pile)
end)ネットワークを経由するため、リモートイベントは少し遅れて届きます。スマートフォンでは、タップも同じクリックです。
チャレンジ
中級PetClient内で、local remotes = game.ReplicatedStorage:WaitForChild("Remotes")とします。マウスのButton1Downで、mouse.TargetがCoinPileという名前のパーツなら、それを指定してremotes.Hitを発火させます。PetServer内で、local remotes = game.ReplicatedStorage.Remotesとし、remotes.Hit.OnServerEventを接続してhitPile(player, pile)を呼び出します。また、spawnPileからClickDetectorを削除し(さらにlocal hitPileの行も削除して、代わりにspawnPileの下にlocal function hitPileと記述します)。
Playを押して、山をクリックします。その後、Checkを押します。
自分で試してみよう
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)
local piles = workspace.Piles
local pileSpot = {} -- 各山 -> その山が置かれている場所
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
pileSpot[pile] = spot
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")
local spot = pileSpot[pile]
pileSpot[pile] = nil
pile:Destroy()
-- 数秒後、同じ場所に新しい山ができる
task.delay(Settings.RespawnTime, spawnPile, spot)
end
-- Meadowのすべての場所に山を置く
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
spawnPile(spot)
end
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。