클릭해서 부수기
Coddy의 Roblox 게임: 펫 시뮬레이터 코스 레슨. 20개 중 6번째.
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 줄은 제거해요. 원격 이벤트가 이를 대체하니까요.
챌린지
중급RemoteEvent를 통해 클릭을 서버로 전송하세요.
PetClient에서:local remotes = game.ReplicatedStorage:WaitForChild("Remotes");local mouse = me:GetMouse();mouse.Button1Down이벤트에서 대상의 이름이CoinPile이면mouse.Target을 사용해remotes.Hit을 호출하세요.PetServer에서:local remotes = game.ReplicatedStorage.Remotes;remotes.Hit.OnServerEvent가hitPile(player, pile)을 호출합니다.- 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")
-- 모든 플레이어에게 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에 놓이는 코인 pile: 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을 공격합니다
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
-- 한 번 공격할 때마다 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 플레이그라운드