Lewati ke konten

Bab 16: Sisi Client - Layar HUD & Kunci Mouse FPS/TPS (StarterPlayerScripts > Controllers > UIController)

Bagian 4 • Tampilan Layar

Script ini menghubungkan antarmuka di layar (HUD) dengan data game. Selain itu, script ini memecahkan masalah klasik game shooter: kursor mouse terkunci di tengah layar saat menembak, dan otomatis muncul kembali saat membuka Toko!

Langkah Pembuatan: Di dalam StarterPlayer > StarterPlayerScripts > Controllers, klik + lalu pilih LocalScript. Beri nama UIController.

StarterPlayerScripts > Controllers > UIController (LocalScript)
--!strict
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")
local Camera = workspace.CurrentCamera
local localPlayer = Players.LocalPlayer
local playerGui = localPlayer:WaitForChild("PlayerGui")
local hud = playerGui:WaitForChild("HUD", 15) :: ScreenGui
if not hud then return end
local Config = require(ReplicatedStorage:WaitForChild("Config") :: ModuleScript)
local SoundManager = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("SoundManager") :: ModuleScript)
local Remotes = ReplicatedStorage:WaitForChild("Remotes")
local GameStateChanged = Remotes:WaitForChild("GameStateChanged") :: RemoteEvent
local WaveInfoUpdated = Remotes:WaitForChild("WaveInfoUpdated") :: RemoteEvent
local PlayerStatsUpdated = Remotes:WaitForChild("PlayerStatsUpdated") :: RemoteEvent
local BossWarning = Remotes:WaitForChild("BossWarning") :: RemoteEvent
local BossHealthUpdated = Remotes:WaitForChild("BossHealthUpdated") :: RemoteEvent
local EquipRequest = Remotes:WaitForChild("EquipRequest") :: RemoteEvent
local ReloadRequest = Remotes:WaitForChild("ReloadRequest") :: RemoteEvent
local AttackRequest = Remotes:WaitForChild("AttackRequest") :: RemoteEvent
local PurchaseRequest = Remotes:WaitForChild("PurchaseRequest") :: RemoteFunction
-- Elemen-Elemen HUD Layar
local topContainer = hud:WaitForChild("TopContainer")
local waveLabel = topContainer:WaitForChild("WaveLabel") :: TextLabel
local statusLabel = topContainer:WaitForChild("StatusLabel") :: TextLabel
local bossContainer = hud:WaitForChild("BossContainer") :: Frame
local bossNameLabel = bossContainer:WaitForChild("BossNameLabel") :: TextLabel
local bossBarFill = bossContainer:WaitForChild("BossBarBg"):WaitForChild("BossBarFill") :: Frame
local blContainer = hud:WaitForChild("BottomLeftContainer")
local hpBarFill = blContainer:WaitForChild("HpBarBg"):WaitForChild("HpBarFill") :: Frame
local hpText = blContainer:WaitForChild("HpBarBg"):WaitForChild("HpText") :: TextLabel
local cashLabel = blContainer:WaitForChild("CashLabel") :: TextLabel
local brContainer = hud:WaitForChild("BottomRightContainer")
local weaponLabel = brContainer:WaitForChild("WeaponLabel") :: TextLabel
local ammoLabel = brContainer:WaitForChild("AmmoLabel") :: TextLabel
local reloadBtn = brContainer:WaitForChild("ReloadBtn") :: TextButton
local quickSlotFrame = brContainer:WaitForChild("QuickSlotFrame")
local shopToggleBtn = hud:WaitForChild("ShopToggleBtn") :: TextButton
local shopModal = hud:WaitForChild("ShopModal") :: Frame
local shopCloseBtn = shopModal:WaitForChild("ShopCloseBtn") :: TextButton
local shopScroll = shopModal:WaitForChild("ShopScroll") :: ScrollingFrame
local gameOverModal = hud:WaitForChild("GameOverModal") :: Frame
local gameOverTitle = gameOverModal:WaitForChild("GameOverTitle") :: TextLabel
local gameOverSubtitle = gameOverModal:WaitForChild("GameOverSubtitle") :: TextLabel
local gameOverCountdown = gameOverModal:WaitForChild("GameOverCountdown") :: TextLabel
local gameOverStroke = gameOverModal:WaitForChild("GameOverStroke") :: UIStroke
local currentStats: any = nil
local populateShopItems: () -> ()
-- Update Tampilan Darah, Uang, dan Peluru
local function updatePlayerHUD(stats: any)
currentStats = stats
if not stats then return end
local hpRatio = math.clamp(stats.Health / stats.MaxHealth, 0, 1)
TweenService:Create(hpBarFill, TweenInfo.new(0.2, Enum.EasingStyle.Quad), {
Size = UDim2.new(hpRatio, 0, 1, 0)
}):Play()
hpText.Text = math.floor(stats.Health) .. " / " .. stats.MaxHealth .. " HP"
if hpRatio > 0.5 then
hpBarFill.BackgroundColor3 = Color3.fromRGB(45, 190, 85)
elseif hpRatio > 0.25 then
hpBarFill.BackgroundColor3 = Color3.fromRGB(220, 160, 40)
else
hpBarFill.BackgroundColor3 = Color3.fromRGB(220, 45, 45)
end
cashLabel.Text = "$ " .. stats.Cash
local curWep = stats.EquippedWeapon or "Pistol"
local wCfg = Config.Weapons[curWep]
if wCfg then
weaponLabel.Text = wCfg.Name
if wCfg.Type == "Melee" then
ammoLabel.Text = "MELEE"
reloadBtn.Visible = false
else
local clip = stats.CurrentAmmo[curWep] or 0
local res = stats.ReserveAmmo[curWep] or 0
ammoLabel.Text = clip .. " / " .. res
reloadBtn.Visible = true
end
end
if shopModal.Visible and populateShopItems then
populateShopItems()
end
end
PlayerStatsUpdated.OnClientEvent:Connect(updatePlayerHUD)
reloadBtn.MouseButton1Click:Connect(function()
if currentStats and currentStats.EquippedWeapon then
ReloadRequest:FireServer(currentStats.EquippedWeapon)
SoundManager.PlaySFX("Reload")
end
end)
local batBtn = quickSlotFrame:WaitForChild("BatSlot") :: TextButton
local pistolBtn = quickSlotFrame:WaitForChild("PistolSlot") :: TextButton
local shotgunBtn = quickSlotFrame:WaitForChild("ShotgunSlot") :: TextButton
batBtn.MouseButton1Click:Connect(function()
EquipRequest:FireServer("Bat")
end)
pistolBtn.MouseButton1Click:Connect(function()
EquipRequest:FireServer("Pistol")
end)
shotgunBtn.MouseButton1Click:Connect(function()
if currentStats and currentStats.UnlockedWeapons.Shotgun then
EquipRequest:FireServer("Shotgun")
else
statusLabel.Text = "Shotgun belum terbuka! Beli di Toko."
end
end)
WaveInfoUpdated.OnClientEvent:Connect(function(waveNum: number, remainingZombies: number, totalZombies: number)
waveLabel.Text = "WAVE " .. waveNum .. " / " .. Config.Game.TotalWaves
statusLabel.Text = "ZOMBIE TERSISA: " .. remainingZombies .. " / " .. totalZombies
end)
GameStateChanged.OnClientEvent:Connect(function(state: string, arg1: any, arg2: any)
if state == "Intermission" then
waveLabel.Text = "WAVE " .. (arg2 or 1) .. " / " .. Config.Game.TotalWaves
statusLabel.Text = "INTERMISI: " .. (arg1 or 0) .. "s (Buka Toko [F])"
bossContainer.Visible = false
gameOverModal.Visible = false
SoundManager.PlayBGM("BGM_Ambient", 1.5)
elseif state == "WaveActive" then
local wNum = arg1 or 1
statusLabel.Text = "WAVE " .. wNum .. " DIMULAI! BERTAHANLAH!"
shopModal.Visible = false
if wNum == 4 or wNum == 5 then
SoundManager.PlayBGM("BGM_Boss", 1.0)
else
SoundManager.PlayBGM("BGM_Ambient", 1.5)
end
elseif state == "WaveClear" then
statusLabel.Text = "WAVE " .. (arg1 or 1) .. " BERSIH! BONUS +$" .. (arg2 or 100)
SoundManager.PlaySFX("WaveClear")
elseif state == "Victory" then
gameOverModal.Visible = true
gameOverTitle.Text = "VICTORY!"
gameOverTitle.TextColor3 = Color3.fromRGB(50, 220, 80)
gameOverStroke.Color = Color3.fromRGB(50, 220, 80)
gameOverSubtitle.Text = "Selamat! Semua 5 Wave zombie berhasil dihabisi!"
gameOverCountdown.Text = "Kembali ke lobi dalam 8 detik..."
SoundManager.StopBGM(1.5)
SoundManager.PlaySFX("WaveClear", nil, 1.2)
elseif state == "Defeat" then
gameOverModal.Visible = true
gameOverTitle.Text = "DEFEAT"
gameOverTitle.TextColor3 = Color3.fromRGB(240, 45, 45)
gameOverStroke.Color = Color3.fromRGB(240, 45, 45)
gameOverSubtitle.Text = "Seluruh pemain telah gugur di Wave " .. (arg1 or 1)
gameOverCountdown.Text = "Mereset permainan dalam 8 detik..."
SoundManager.StopBGM(1.5)
elseif state == "Reset" then
gameOverModal.Visible = false
bossContainer.Visible = false
SoundManager.PlayBGM("BGM_Ambient", 1.5)
end
end)
BossWarning.OnClientEvent:Connect(function(bossName: string)
bossContainer.Visible = true
bossNameLabel.Text = bossName
bossBarFill.Size = UDim2.new(1, 0, 1, 0)
statusLabel.Text = "PERINGATAN: " .. bossName .. " MUNCUL!"
SoundManager.PlayBGM("BGM_Boss", 0.8)
end)
BossHealthUpdated.OnClientEvent:Connect(function(bossName: string, curHp: number, maxHp: number)
if curHp <= 0 then
bossContainer.Visible = false
else
bossContainer.Visible = true
bossNameLabel.Text = bossName
local ratio = math.clamp(curHp / maxHp, 0, 1)
TweenService:Create(bossBarFill, TweenInfo.new(0.15, Enum.EasingStyle.Quad), {
Size = UDim2.new(ratio, 0, 1, 0)
}):Play()
end
end)
-- Sistem Toko Belanja Interaktif
populateShopItems = function()
shopScroll:ClearAllChildren()
local layout = Instance.new("UIListLayout")
layout.Padding = UDim.new(0, 8)
layout.Parent = shopScroll
local itemOrder = { "HealPack", "AmmoRefill", "MaxHealthUpgrade", "SpeedUpgrade", "DamageUpgrade", "ShotgunUnlock" }
for _, itemId in ipairs(itemOrder) do
local upCfg = Config.Upgrades[itemId]
if not upCfg then continue end
local itemCard = Instance.new("Frame")
itemCard.Name = itemId .. "Card"
itemCard.Size = UDim2.new(0.98, 0, 0, 60)
itemCard.BackgroundColor3 = Color3.fromRGB(28, 32, 38)
itemCard.BorderSizePixel = 0
itemCard.Parent = shopScroll
local c = Instance.new("UICorner")
c.CornerRadius = UDim.new(0, 8)
c.Parent = itemCard
local nameLabel = Instance.new("TextLabel")
nameLabel.Position = UDim2.new(0.03, 0, 0.1, 0)
nameLabel.Size = UDim2.new(0.65, 0, 0.4, 0)
nameLabel.BackgroundTransparency = 1
nameLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
nameLabel.TextSize = 14
nameLabel.Font = Enum.Font.GothamBold
nameLabel.TextXAlignment = Enum.TextXAlignment.Left
nameLabel.Parent = itemCard
local descLabel = Instance.new("TextLabel")
descLabel.Position = UDim2.new(0.03, 0, 0.52, 0)
descLabel.Size = UDim2.new(0.65, 0, 0.38, 0)
descLabel.BackgroundTransparency = 1
descLabel.TextColor3 = Color3.fromRGB(180, 190, 200)
descLabel.TextSize = 12
descLabel.Font = Enum.Font.GothamMedium
descLabel.TextXAlignment = Enum.TextXAlignment.Left
descLabel.Text = upCfg.Description
descLabel.Parent = itemCard
local buyBtn = Instance.new("TextButton")
buyBtn.AnchorPoint = Vector2.new(1, 0.5)
buyBtn.Position = UDim2.new(0.97, 0, 0.5, 0)
buyBtn.Size = UDim2.new(0.26, 0, 0.7, 0)
buyBtn.BackgroundColor3 = Color3.fromRGB(45, 140, 75)
buyBtn.TextColor3 = Color3.fromRGB(255, 255, 255)
buyBtn.TextSize = 13
buyBtn.Font = Enum.Font.GothamBold
buyBtn.Parent = itemCard
local btnCorner = Instance.new("UICorner")
btnCorner.CornerRadius = UDim.new(0, 6)
btnCorner.Parent = buyBtn
if upCfg.Type == "Tiered" then
local curTier = (currentStats and currentStats.Upgrades[itemId]) or 0
if curTier >= upCfg.MaxTier then
nameLabel.Text = upCfg.Name .. " (MAX)"
buyBtn.Text = "MAKSIMAL"
buyBtn.BackgroundColor3 = Color3.fromRGB(70, 75, 80)
buyBtn.Active = false
else
local cost = upCfg.BaseCost + (curTier * upCfg.CostScale)
nameLabel.Text = upCfg.Name .. " (Lv " .. curTier .. "/" .. upCfg.MaxTier .. ")"
buyBtn.Text = "BELI ($" .. cost .. ")"
end
elseif itemId == "ShotgunUnlock" then
local unlocked = currentStats and currentStats.UnlockedWeapons.Shotgun
if unlocked then
nameLabel.Text = upCfg.Name .. " (TERBUKA)"
buyBtn.Text = "DIMILIKI"
buyBtn.BackgroundColor3 = Color3.fromRGB(70, 75, 80)
buyBtn.Active = false
else
nameLabel.Text = upCfg.Name
buyBtn.Text = "BELI ($" .. upCfg.Cost .. ")"
end
else
nameLabel.Text = upCfg.Name
buyBtn.Text = "BELI ($" .. upCfg.Cost .. ")"
end
buyBtn.MouseButton1Click:Connect(function()
local success, msg = PurchaseRequest:InvokeServer(itemId)
statusLabel.Text = msg
if success then
SoundManager.PlaySFX("CashBuy")
end
end)
end
end
local function toggleShop()
shopModal.Visible = not shopModal.Visible
if shopModal.Visible then
populateShopItems()
end
end
shopToggleBtn.MouseButton1Click:Connect(toggleShop)
shopCloseBtn.MouseButton1Click:Connect(function()
shopModal.Visible = false
end)
UserInputService.InputBegan:Connect(function(input, gpe)
if gpe then return end
if input.KeyCode == Enum.KeyCode.F then
toggleShop()
end
end)
task.spawn(function()
task.wait(0.3)
local initState = ReplicatedStorage:GetAttribute("CurrentState")
local initWave = ReplicatedStorage:GetAttribute("CurrentWave") or 1
if initState == "WaveActive" and (initWave == 4 or initWave == 5) then
SoundManager.PlayBGM("BGM_Boss", 1.0)
else
SoundManager.PlayBGM("BGM_Ambient", 1.5)
end
end)
-- PENGATURAN MOUSE KURSOR & KUNCI BIDIKAN FPS/TPS
-- Saat bermain tempur: Kursor panah disembunyikan dan dikunci ke tengah (LockCenter).
-- Saat membuka toko [F] / game over: Kursor panah dimunculkan kembali untuk klik tombol belanja!
local isCursorFree = false
UserInputService.InputBegan:Connect(function(input, gpe)
if gpe then return end
if input.KeyCode == Enum.KeyCode.LeftAlt or input.KeyCode == Enum.KeyCode.RightAlt then
isCursorFree = not isCursorFree
end
end)
RunService.RenderStepped:Connect(function()
local inMenu = (shopModal and shopModal.Visible) or (gameOverModal and gameOverModal.Visible) or isCursorFree
if inMenu then
UserInputService.MouseIconEnabled = true
UserInputService.MouseBehavior = Enum.MouseBehavior.Default
else
UserInputService.MouseIconEnabled = false
UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
end
end)
  • Solusi Kursor Mouse Stuck di FPS/TPS: Di baris 372-380, saat berada di arena tempur, script mengatur MouseIconEnabled = false dan MouseBehavior = LockCenter. Kursor panah putih Windows/Roblox tidak akan pernah menghalangi crosshair saat kamu scroll zoom in/out!
  • Otomatis Membuka Kursor Saat Belanja: Begitu kamu menekan tombol [F] untuk membuka Toko, kursor mouse otomatis muncul kembali sehingga kamu bisa leluasa mengklik tombol upgrade item.
  • Transisi Halus Bar Darah (TweenService): Ketika darah berkurang atau pulih, panjang bar hijau tidak melompat patah-patah melainkan bergeser mulus dalam 0.2 detik, dan berubah warna menjadi kuning/merah saat sekarat.