Menu
CoddyTech

クリックして壊そう

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

ボタンには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)

リモートはネットワークを経由するため、少し遅れて届きます。スマートフォンでは、タップもクリックと同じです。ClickDetectorと、レッスン3にあるlocal hitPileの行は不要です。リモートがそれらに置き換わります。

challenge icon

チャレンジ

中級

RemoteEventを通じてクリックをサーバーに送信します。

  1. PetClientでは、local remotes = game.ReplicatedStorage:WaitForChild("Remotes")、local mouse = me:GetMouse()を記述します。mouse.Button1Downで、名前がCoinPileのときにmouse.Targetを指定してremotes.Hitを発火させます。
  2. PetServerでは、local remotes = game.ReplicatedStorage.Remotesを記述します。remotes.Hit.OnServerEventはhitPile(player, pile)を呼び出します。
  3. ClickDetectorの行とlocal hitPileを削除し、local function hitPileと記述します。

「プレイ」を押して山をクリックすると、これまでと同じように壊れます。その後、「確認」を押します。

自分で試してみよう

local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)

local piles = workspace.Piles
local pileSpot = {} -- 各pile -> そのpileが置かれているspot

print("A Meadow pile gives " .. Settings.PileValue .. " coins")

-- すべてのplayerにleaderboard上の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)

-- pileのクリック処理には、spawnPileの後で定義されるhitPileが必要なので、
-- 両方より前のここで宣言する
local hitPile

-- spot上のコインの山: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回ヒットするとpileの体力が1減る。
-- 0になるとpileが壊れ、その価値に応じたコインが支払われる
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()
	-- 数秒後に同じspotに新しいpileを生成する
	task.delay(Settings.RespawnTime, spawnPile, spot)
end

-- Meadowの各spotにpileを配置する
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
	spawnPile(spot)
end

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

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