Menu
CoddyTech

屏幕上的金币

Coddy Roblox 游戏:宠物模拟器 课程的第 5 课,共 20 课。

现在来看客户端。PetClient 是 HUD 中的一个 LocalScript。HUD 是一个 ScreenGui,玩家生成时,Roblox 会将它从 StarterGui 复制到每位玩家的屏幕上。LocalScript 会在该玩家自己的设备上运行,并且可以指定它所对应的玩家:

local me = game:GetService("Players").LocalPlayer

在服务器 Script 中,LocalPlayer 的值为 nil:服务器会同时为所有玩家提供服务。

玩家加入后,服务器会过一会儿才把 leaderstats 放入玩家对象,因此客户端会用 WaitForChild 等待它。然后,客户端会在 HUD 的 Coins 标签中显示金币数量,并在每次金币数量变化时再次更新:IntValue 的 Changed 会在数值变化时触发,并传入新值。

这个标签只显示服务器确定的内容。在 LocalScript 中更改 Coins.Value,只会改变这位玩家看到的内容,不会改变服务器上的内容。

challenge icon

挑战

中等

在玩家的屏幕上显示金币数量。

  1. 在 PetClient 中:local Players = game:GetService("Players")、local me = Players.LocalPlayer、local hud = script.Parent。
  2. local coins = me:WaitForChild("leaderstats"):WaitForChild("Coins")
  3. 编写 showCoins():hud.Coins.Text = "Coins: " .. coins.Value。调用一次,并将它连接到 coins.Changed。

按“开始”并打破一堆金币:左上角会显示 Coins: 5。然后按“检查”。

亲手试试

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)

-- 点击金币堆时需要用到 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
	pileSpot[pile] = spot
	pile.Parent = piles
	detector.MouseClick:Connect(function(player)
		hitPile(player, pile)
	end)
	return pile
end

-- 每次攻击让金币堆的生命值减少 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

Roblox 游戏:宠物模拟器中的所有课

自己练习: Roblox 在线编辑器