내 펫 목록
Coddy의 Roblox 게임: 펫 시뮬레이터 코스 레슨. 18개 중 13번째.
플레이어는 자신의 펫을 볼 수 있어야 합니다. HUD에는 Inventory ScrollingFrame이 있고, 그 안에 UIListLayout이 있어 내부의 항목을 LayoutOrder에 따라 위에서 아래로 쌓습니다. 각 펫은 여기에 TextButton으로 표시됩니다. AutomaticCanvasSize가 Y로 설정되어 있어 목록이 늘어나면 캔버스도 커지며, 펫이 많은 플레이어는 스크롤해서 볼 수 있습니다.
클라이언트는 서버가 플레이어 안에 보관하는 Pets 폴더에서 목록을 만들고, 폴더가 변경되면 목록을 다시 만듭니다. 펫이 부화하면 ChildAdded가 발생하고, 펫이 장착되거나 장착 해제될 때는 각 펫의 GetAttributeChangedSignal("Equipped")이 발생합니다.
pet:GetAttributeChangedSignal("Equipped"):Connect(showPets)목록을 다시 만들 때는 먼저 기존 버튼을 제거하므로, 목록에 같은 펫이 두 번 표시되지 않습니다.
챌린지
중급PetClient에서:
- 플레이어의
Pets를 기다립니다. showPets()를 작성합니다.hud.Inventory의 TextButton을 제거한 다음, 각 펫마다 하나씩 추가합니다(LayoutOrder는 순서, 너비는UDim2.new(1, -12, 0, 30), 흰색 크기 조정 텍스트). 밖에 나와 있는 펫은Cat (out), 그렇지 않은 펫은Cat으로 표시하고, 밖에 나와 있을 때는 초록색으로 표시합니다.- 지금, 펫이 추가될 때, 그리고 어떤 펫이든
Equipped가 변경될 때 이 함수를 호출합니다.
Play를 누르고 알을 부화시킵니다. 그런 다음 Check를 누릅니다.
직접 해보기
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 pile = ServerStorage.CoinPile:Clone()
pile.Position = spot.Position
pile:SetAttribute("MaxHealth", Settings.PileHealth)
pile:SetAttribute("Health", Settings.PileHealth)
pile:SetAttribute("Value", Settings.PileValue)
pile.HealthGui.Label.Text = pile:GetAttribute("Health") .. "/" .. pile:GetAttribute("MaxHealth")
pileSpot[pile] = spot
pile.Parent = piles
return pile
end
-- 공격할 때마다 코인 더미의 체력이 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
-- Meadow의 모든 위치에 코인 더미를 생성한다
for _, spot in workspace.Zones.Meadow.Spawns:GetChildren() do
spawnPile(spot)
end
-- 클라이언트가 코인 더미를 타격하겠다고 요청한다. 클라이언트를 절대 신뢰하지 말 것: 누구나
-- 어디서든 원하는 데이터를 담아 원하는 만큼 빠르게 이 remote를 호출할 수 있다.
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
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)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.