Bab 15: Sisi Client - Kontrol Tembak & Animasi (StarterPlayerScripts > Controllers > WeaponController)
Bagian 4 • Sisi Client
Script ini berjalan di laptop/HP pemain. Tugasnya membaca klik mouse untuk menembak, tombol R untuk mengisi peluru, angka 1, 2, 3 untuk mengganti senjata, serta memainkan kilatan api senjata (muzzle flash) dan ayunan bat secara mulus.
Langkah Pembuatan: Di dalam StarterPlayer > StarterPlayerScripts > Controllers, klik + lalu pilih LocalScript. Beri nama WeaponController.
--!strictlocal Players = game:GetService("Players")local UserInputService = game:GetService("UserInputService")local ReplicatedStorage = game:GetService("ReplicatedStorage")local RunService = game:GetService("RunService")local TweenService = game:GetService("TweenService")local Debris = game:GetService("Debris")
local localPlayer = Players.LocalPlayerlocal Camera = workspace.CurrentCamera
local Config = require(ReplicatedStorage:WaitForChild("Config") :: ModuleScript)local SoundManager = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("SoundManager") :: ModuleScript)local Remotes = ReplicatedStorage:WaitForChild("Remotes")local AttackRequest = Remotes:WaitForChild("AttackRequest") :: RemoteEventlocal ReloadRequest = Remotes:WaitForChild("ReloadRequest") :: RemoteEventlocal EquipRequest = Remotes:WaitForChild("EquipRequest") :: RemoteEventlocal PlayerStatsUpdated = Remotes:WaitForChild("PlayerStatsUpdated") :: RemoteEventlocal HitConfirm = Remotes:WaitForChild("HitConfirm") :: RemoteEvent
local currentStats: any = nillocal lastFireTime = 0local isMouseDown = falselocal loadedMeleeAnim: AnimationTrack? = nillocal lastLoadedChar: Model? = nil
local playerGui = localPlayer:WaitForChild("PlayerGui")local hud = playerGui:WaitForChild("HUD", 15) :: ScreenGui?local crosshair = hud and hud:WaitForChild("Crosshair", 5) :: Frame?local hitMarker = crosshair and crosshair:WaitForChild("HitMarker", 5) :: Frame?
PlayerStatsUpdated.OnClientEvent:Connect(function(data) currentStats = dataend)
-- Tanda Hit Marker di Crosshairlocal function showHitMarker(isHeadshot: boolean) if not hitMarker then return end local color = isHeadshot and Color3.fromRGB(255, 60, 60) or Color3.fromRGB(255, 255, 255) for _, child in ipairs(hitMarker:GetChildren()) do if child:IsA("Frame") then child.BackgroundColor3 = color end end hitMarker.Visible = true task.delay(0.12, function() if hitMarker then hitMarker.Visible = false end end)end
HitConfirm.OnClientEvent:Connect(function(isHeadshot: boolean) showHitMarker(isHeadshot) SoundManager.PlaySFX("BatHit", nil, isHeadshot and 1.2 or 0.85)end)
-- Load Animasi Ayunan Batlocal function getMeleeAnimTrack(): AnimationTrack? local char = localPlayer.Character if not char then return nil end
if char == lastLoadedChar and loadedMeleeAnim then return loadedMeleeAnim end
local hum = char:FindFirstChildOfClass("Humanoid") if not hum then return nil end
local animator = hum:FindFirstChildOfClass("Animator") if not animator then animator = Instance.new("Animator") animator.Parent = hum end
local isR15 = hum.RigType == Enum.HumanoidRigType.R15 local anim = Instance.new("Animation") anim.AnimationId = isR15 and "rbxassetid://522635533" or "rbxassetid://129967390"
local success, track = pcall(function() return animator:LoadAnimation(anim) end)
if success and track then track.Priority = Enum.AnimationPriority.Action loadedMeleeAnim = track lastLoadedChar = char return track end return nilend
local function getAimDirection(): (Vector3, Vector3) local char = localPlayer.Character local hrp = char and char:FindFirstChild("HumanoidRootPart") :: BasePart? local origin = hrp and (hrp.Position + Vector3.new(0, 1.5, 0)) or Vector3.new(0, 5, 0)
local viewportSize = Camera.ViewportSize local centerScreen = Vector2.new(viewportSize.X / 2, viewportSize.Y / 2) local unitRay = Camera:ViewportPointToRay(centerScreen.X, centerScreen.Y)
local raycastParams = RaycastParams.new() if char then raycastParams.FilterDescendantsInstances = { char } raycastParams.FilterType = Enum.RaycastFilterType.Exclude end
local result = workspace:Raycast(unitRay.Origin, unitRay.Direction * 500, raycastParams) local targetPos = result and result.Position or (unitRay.Origin + unitRay.Direction * 200) local dir = (targetPos - origin).Unit
return origin, dirend
-- Efek Ayunan Bat & Trail Sayatanlocal function playMeleeSwingVisuals() local track = getMeleeAnimTrack() if track then track:Play(0.05, 1, 1.8) end
local char = localPlayer.Character local wepVisual = char and char:FindFirstChild("EquippedWeaponVisual") local handle = wepVisual and (wepVisual.PrimaryPart or wepVisual:FindFirstChild("Handle")) local weld = handle and handle:FindFirstChild("WeaponWeld") :: Weld?
if weld then local baseC0 = CFrame.new(0, -0.85, -0.2) * CFrame.Angles(math.rad(-50), 0, 0) local swingC0 = CFrame.new(0, -0.6, -1.0) * CFrame.Angles(math.rad(-115), math.rad(-30), math.rad(-20))
local forwardTween = TweenService:Create(weld, TweenInfo.new(0.12, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), { C0 = swingC0 }) forwardTween:Play()
forwardTween.Completed:Connect(function() local returnTween = TweenService:Create(weld, TweenInfo.new(0.18, Enum.EasingStyle.Quad, Enum.EasingDirection.In), { C0 = baseC0 }) returnTween:Play() end) end
if handle then local slashPart = Instance.new("Part") slashPart.Size = Vector3.new(0.4, 0.4, 0.4) slashPart.CFrame = handle.CFrame * CFrame.new(0, 1.5, 0) slashPart.Transparency = 1 slashPart.CanCollide = false slashPart.Anchored = true slashPart.Parent = workspace
local att = Instance.new("Attachment") att.Parent = slashPart
local particles = Instance.new("ParticleEmitter") particles.Color = ColorSequence.new(Color3.fromRGB(255, 255, 230), Color3.fromRGB(220, 180, 80)) particles.Size = NumberSequence.new({ NumberSequenceKeypoint.new(0, 1.5), NumberSequenceKeypoint.new(1, 0.2) }) particles.Transparency = NumberSequence.new({ NumberSequenceKeypoint.new(0, 0.2), NumberSequenceKeypoint.new(1, 1.0) }) particles.Lifetime = NumberRange.new(0.15, 0.25) particles.Rate = 0 particles.Speed = NumberRange.new(5, 10) particles.SpreadAngle = Vector2.new(180, 45) particles.Parent = att
particles:Emit(12) Debris:AddItem(slashPart, 0.3) endend
local function playLocalMuzzleFlash() local char = localPlayer.Character if not char then return end
local rightArm = char:FindFirstChild("RightHand") or char:FindFirstChild("Right Arm") if not rightArm or not rightArm:IsA("BasePart") then return end
local light = Instance.new("PointLight") light.Color = Color3.fromRGB(255, 230, 150) light.Range = 14 light.Brightness = 4 light.Parent = rightArm task.delay(0.06, function() light:Destroy() end)
if crosshair then crosshair.Size = UDim2.new(0, 44, 0, 44) TweenService:Create(crosshair, TweenInfo.new(0.15, Enum.EasingStyle.Quad), { Size = UDim2.new(0, 36, 0, 36) }):Play() endend
local function tryAttack() if not currentStats or not currentStats.IsAlive then return end
local weaponKey = currentStats.EquippedWeapon local wCfg = Config.Weapons[weaponKey] if not wCfg then return end
local now = os.clock() if now - lastFireTime < wCfg.AttackCooldown then return end
if wCfg.Type == "Ranged" then local clip = currentStats.CurrentAmmo[weaponKey] or 0 if clip <= 0 then ReloadRequest:FireServer(weaponKey) SoundManager.PlaySFX("Reload") return end end
lastFireTime = now local origin, dir = getAimDirection() AttackRequest:FireServer(weaponKey, origin, dir)
if wCfg.Type == "Melee" then playMeleeSwingVisuals() SoundManager.PlaySFX("BatSwing") else playLocalMuzzleFlash() if weaponKey == "Pistol" then SoundManager.PlaySFX("PistolShot") elseif weaponKey == "Shotgun" then SoundManager.PlaySFX("ShotgunShot") end endend
UserInputService.InputBegan:Connect(function(input, gameProcessed) if gameProcessed then return end
if input.UserInputType == Enum.UserInputType.MouseButton1 then isMouseDown = true tryAttack() end
if input.KeyCode == Enum.KeyCode.R then if currentStats and currentStats.EquippedWeapon then local curWep = currentStats.EquippedWeapon local wCfg = Config.Weapons[curWep] if wCfg and wCfg.Type == "Ranged" then ReloadRequest:FireServer(curWep) SoundManager.PlaySFX("Reload") end end end
if input.KeyCode == Enum.KeyCode.One then EquipRequest:FireServer("Bat") elseif input.KeyCode == Enum.KeyCode.Two then EquipRequest:FireServer("Pistol") elseif input.KeyCode == Enum.KeyCode.Three then EquipRequest:FireServer("Shotgun") endend)
UserInputService.InputEnded:Connect(function(input, _gameProcessed) if input.UserInputType == Enum.UserInputType.MouseButton1 then isMouseDown = false endend)
RunService.Heartbeat:Connect(function() if isMouseDown then tryAttack() endend)Fitur Keren Sisi Pemain:
Section titled “Fitur Keren Sisi Pemain:”- Bidikan Tepat di Tengah Layar: Fungsi
getAimDirectionmenembakkan sinar dari tengah kamera persis di posisi crosshair bidikan, sehingga kemanapun kamu mengarahkan kamera, peluru akan melesat lurus ke sana. - Animasi Ayunan Bat Prosedural: Menggunakan
TweenServiceuntuk memutar sudut model bat ke depan dalam 0.12 detik lalu kembali ke posisi siap, ditambah partikel jejak tebasan pedang/bat kuning menyala. - Crosshair Recoil Pulse: Setiap kali menembak, ukuran bidikan crosshair sedikit membesar (44px) lalu mengecil kembali (36px) untuk mensimulasikan hentakan senjata.