Menu
CoddyTech

珍しいペットのニュース

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

誰かがレジェンダリーのペットを孵化させたら、サーバー全体に知らせる必要があります。FireAllClientsは、すべてのプレイヤーのクライアントで同時にRemoteEventを発火させます:

-- サーバー
remotes.Announce:FireAllClients(player.Name, name)
-- クライアント
remotes.Announce.OnClientEvent:Connect(function(who, pet)
end)

各クライアントは、HUDのBannerに数秒間ニュースを表示します。OnClientEventが受け取るのは、サーバーが送信した内容そのものです。この側でプレイヤーが追加されることはありません。

challenge icon

チャレンジ

難しい
  1. PetServer で、ペットが孵化した後、その Rarity が Legendary の場合、プレイヤーの Name とペットの名前を添えて、すべてのクライアントに remotes.Announce を発火させます。
  2. PetClient で、remotes.Announce.OnClientEvent が発生したとき、Banner のテキストを Player1 hatched a Dragon! に設定し、表示して、4 秒待ってから非表示にします。

Play を押してから Check を押します。チェックによって Dragon が孵化します。

自分で試してみよう

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

local remotes = game.ReplicatedStorage.Remotes
local piles = workspace.Piles
local petParts = workspace.PetParts
local pileSpot = {} -- 各コインの山 -> その山が置かれている場所
local lastHit = {} -- 各プレイヤー -> 最後に叩いた時刻

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

-- 名前をキーにしたSettings.Pets
local petInfo = {}
for _, info in Settings.Pets do
	petInfo[info.Name] = info
end

-- ペット:プレイヤーのPetsフォルダーにある、名前を保持するStringValueで、
-- レア度とパワーを属性として持つ
local function givePet(player, name, equipped)
	local info = petInfo[name]
	local pet = Instance.new("StringValue")
	pet.Name = "Pet"
	pet.Value = name
	pet:SetAttribute("Rarity", info.Rarity)
	pet:SetAttribute("Power", info.Power)
	pet:SetAttribute("Equipped", equipped)
	pet.Parent = player.Pets
	return pet
end

-- プレイヤーが出しているペットの数
local function equippedCount(player)
	local count = 0
	for _, pet in player.Pets:GetChildren() do
		if pet:GetAttribute("Equipped") then
			count += 1
		end
	end
	return count
end

-- プレイヤーのペットが各攻撃に加えるパワー
local function petPower(player)
	local power = 0
	for _, pet in player.Pets:GetChildren() do
		if pet:GetAttribute("Equipped") then
			power += pet:GetAttribute("Power")
		end
	end
	return power
end

-- すべてのプレイヤーのリーダーボードに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

	-- プレイヤーが所有するペット
	local pets = Instance.new("Folder")
	pets.Name = "Pets"
	pets.Parent = player
end)

-- 場所に置かれるコインの山:ServerStorage.CoinPileのコピーで、体力と
-- 価値を属性として持つ
local function spawnPile(spot)
	local desert = spot.Parent.Parent.Name == "Desert"
	local health = desert and Settings.DesertHealth or Settings.PileHealth
	local pile = ServerStorage.CoinPile:Clone()
	pile.Position = spot.Position
	pile:SetAttribute("MaxHealth", health)
	pile:SetAttribute("Health", health)
	pile:SetAttribute("Value", desert and Settings.DesertValue or Settings.PileValue)
	pile:SetAttribute("Zone", spot.Parent.Parent.Name)
	pile.HealthGui.Label.Text = pile:GetAttribute("Health") .. "/" .. pile:GetAttribute("MaxHealth")
	pileSpot[pile] = spot
	pile.Parent = piles
	return pile
end

-- 1回叩くと、山の体力が1とプレイヤーのペットのパワーの合計だけ減る;
-- 0になると山が壊れ、その価値に応じたコインが支払われる
local function hitPile(player, pile)
	local health = pile:GetAttribute("Health") - (1 + petPower(player))
	if health > 0 then
		pile:SetAttribute("Health", health)
		pile.HealthGui.Label.Text = health .. "/" .. pile:GetAttribute("MaxHealth")
		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

-- すべてのゾーンのすべての場所に山を作る
for _, zone in workspace.Zones:GetChildren() do
	for _, spot in zone.Spawns:GetChildren() do
		spawnPile(spot)
	end
end

-- クライアントは山を叩くよう要求する。クライアントを決して信用しないこと。誰でも
-- どこからでも、何を引数にしても、好きな速さでこのリモートイベントを発火できる。
remotes.Hit.OnServerEvent:Connect(function(player, pile)
	-- 実在する山か
	if typeof(pile) ~= "Instance" or pile.Parent ~= piles then
		return
	end
	-- 手が届く範囲か
	local character = player.Character
	local root = character and character:FindFirstChild("HumanoidRootPart")
	if not root or (root.Position - pile.Position).Magnitude > Settings.Reach then
		return
	end
	-- 速すぎないか
	local now = time()
	if lastHit[player] and now - lastHit[player] < Settings.HitCooldown then
		return
	end
	lastHit[player] = now
	-- プレイヤーが解放したゾーン内か
	if pile:GetAttribute("Zone") == "Desert" and not player:GetAttribute("Desert") then
		return
	end
	hitPile(player, pile)
end)

-- 重み付き抽選:各ペットのChance(100を基準とする)が全体に占める割合になる
local function rollPet()
	local roll = math.random() * 100
	for _, info in Settings.Pets do
		roll -= info.Chance
		if roll <= 0 then
			return info.Name
		end
	end
	return Settings.Pets[1].Name
end

-- 孵化:卵のプロンプトで、コインを支払って行う
workspace.Egg.ProximityPrompt.Triggered:Connect(function(player)
	local coins = player.leaderstats.Coins
	if coins.Value < Settings.EggPrice then
		return
	end
	coins.Value -= Settings.EggPrice
	local name = rollPet()
	-- 空きがあれば、すぐに外に出す
	local pet = givePet(player, name, equippedCount(player) < Settings.MaxEquipped)
	print(player.Name .. " hatched a " .. name)
end)

-- 外に出ているペットは飼い主についていく。各ペットに対応するパーツがワールド内にあり、
-- 毎フレーム、プレイヤーの後ろに一列に配置される
local petModels = {} -- 各ペット -> ワールド内で対応するパーツ
RunService.Heartbeat:Connect(function()
	for _, player in Players:GetPlayers() do
		local root = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
		local pets = player:FindFirstChild("Pets")
		local slot = 0
		for _, pet in pets and pets:GetChildren() or {} do
			local model = petModels[pet]
			if pet:GetAttribute("Equipped") and root then
				slot += 1
				if not model then
					model = ServerStorage.PetModels[pet.Value]:Clone()
					model.Parent = petParts
					petModels[pet] = model
				end
				model.CFrame = root.CFrame * CFrame.new((slot - 2) * 3, -1.5, 4)
			elseif model then
				model:Destroy()
				petModels[pet] = nil
			end
		end
	end
end)

-- クライアントはペットを出すか戻すかを要求する。サーバーは、そのペットが
-- プレイヤー自身のもので、出ている数がMaxEquipped以下かを確認する。
remotes.Equip.OnServerEvent:Connect(function(player, pet)
	if typeof(pet) ~= "Instance" or pet.Parent ~= player.Pets then
		return
	end
	if pet:GetAttribute("Equipped") then
		pet:SetAttribute("Equipped", false)
	elseif equippedCount(player) < Settings.MaxEquipped then
		pet:SetAttribute("Equipped", true)
	end
end)

-- Desertのゲート:一度支払うと、そのプレイヤーにだけ開く
workspace.Gate.ProximityPrompt.Triggered:Connect(function(player)
	local coins = player.leaderstats.Coins
	if player:GetAttribute("Desert") or coins.Value < Settings.GatePrice then
		return
	end
	coins.Value -= Settings.GatePrice
	player:SetAttribute("Desert", true)
end)
quiz icon腕試し

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

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