Lewati ke konten

Bab 11: Otak Zombie AI & Boss Fight (ServerScriptService > Services > EnemyService)

Bagian 3 • Musuh & AI

Inilah script paling seru sekaligus paling cerdas di game kita! Modul ini mengatur bagaimana zombie berpikir, mendeteksi posisi pemain, berlari mengejar, dan melancarkan jurus-jurus maut.

Langkah Pembuatan: Di dalam ServerScriptService > Services, klik + lalu pilih ModuleScript. Beri nama EnemyService.

ServerScriptService > Services > EnemyService (ModuleScript)
--!strict
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local Debris = game:GetService("Debris")
local TweenService = game:GetService("TweenService")
local Config = require(ReplicatedStorage:WaitForChild("Config") :: ModuleScript)
local Signal = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("Signal") :: ModuleScript)
local SoundManager = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("SoundManager") :: ModuleScript)
local Remotes = ReplicatedStorage:WaitForChild("Remotes")
local BossWarning = Remotes:WaitForChild("BossWarning") :: RemoteEvent
local BossHealthUpdated = Remotes:WaitForChild("BossHealthUpdated") :: RemoteEvent
local PlayerDataService = require(script.Parent:WaitForChild("PlayerDataService") :: ModuleScript)
local CombatService = require(script.Parent:WaitForChild("CombatService") :: ModuleScript)
local EnemyService = {}
local activeZombies: { [Model]: boolean } = {}
local enemiesFolder = ServerStorage:WaitForChild("Enemies")
local function getZombiesContainer(): Folder
local folder = workspace:FindFirstChild("Zombies")
if not folder then
folder = Instance.new("Folder")
folder.Name = "Zombies"
folder.Parent = workspace
end
return folder :: Folder
end
-- Mencari pemain hidup terdekat
local function findClosestPlayer(fromPos: Vector3): (Player?, Model?, number)
local closestPlayer: Player? = nil
local closestChar: Model? = nil
local shortestDist = math.huge
for _, player in ipairs(Players:GetPlayers()) do
local pData = PlayerDataService.Get(player)
if pData and pData.IsAlive then
local char = player.Character
local hrp = char and char:FindFirstChild("HumanoidRootPart") :: BasePart?
local hum = char and char:FindFirstChildOfClass("Humanoid")
if hrp and hum and hum.Health > 0 then
local dist = (hrp.Position - fromPos).Magnitude
if dist < shortestDist then
shortestDist = dist
closestPlayer = player
closestChar = char
end
end
end
end
return closestPlayer, closestChar, shortestDist
end
-- Genangan Asam Spitter
local function createAcidPuddle(pos: Vector3, duration: number, dps: number)
local puddle = Instance.new("Part")
puddle.Name = "AcidPuddle"
puddle.Size = Vector3.new(10, 0.2, 10)
puddle.Position = pos + Vector3.new(0, 0.1, 0)
puddle.Anchored = true
puddle.CanCollide = false
puddle.Material = Enum.Material.Neon
puddle.Color = Color3.fromRGB(80, 220, 40)
puddle.Transparency = 0.35
puddle.Parent = workspace
Debris:AddItem(puddle, duration)
task.spawn(function()
local elapsed = 0
while elapsed < duration and puddle.Parent do
for _, player in ipairs(Players:GetPlayers()) do
local char = player.Character
local hrp = char and char:FindFirstChild("HumanoidRootPart") :: BasePart?
if hrp and (hrp.Position - puddle.Position).Magnitude <= 5.5 then
CombatService.DamagePlayer(player, dps)
end
end
task.wait(0.5)
elapsed += 0.5
end
end)
end
-- Tembakan Bola Ludah Asam Spitter
local function fireAcidProjectile(fromPos: Vector3, targetPos: Vector3, damage: number, puddleDuration: number, puddleDps: number)
local proj = Instance.new("Part")
proj.Name = "AcidSpit"
proj.Size = Vector3.new(1.4, 1.4, 1.4)
proj.Position = fromPos
proj.CanCollide = false
proj.Material = Enum.Material.Neon
proj.Color = Color3.fromRGB(100, 255, 50)
proj.Parent = workspace
local bv = Instance.new("BodyVelocity")
local dir = (targetPos - fromPos).Unit
local dist = (targetPos - fromPos).Magnitude
bv.Velocity = (dir * 45) + Vector3.new(0, math.clamp(dist * 0.25, 2, 10), 0)
bv.MaxForce = Vector3.new(1e5, 1e5, 1e5)
bv.Parent = proj
local connection: RBXScriptConnection? = nil
local hasHit = false
local function onHit(hitPart: BasePart?)
if hasHit then return end
hasHit = true
if connection then
connection:Disconnect()
connection = nil
end
local hitPos = proj.Position
proj:Destroy()
if hitPart then
local char = hitPart:FindFirstAncestorOfClass("Model")
local player = char and Players:GetPlayerFromCharacter(char)
if player then
CombatService.DamagePlayer(player, damage)
end
end
createAcidPuddle(hitPos, puddleDuration, puddleDps)
end
connection = proj.Touched:Connect(function(hit)
local model = hit:FindFirstAncestorOfClass("Model")
if model and model:GetAttribute("IsZombie") then return end
onHit(hit)
end)
task.delay(3, function()
if not hasHit then
onHit(nil)
end
end)
end
-- Hentakan Tanah Boss dengan Lingkaran Merah Peringatan (Telegraph)
local function performBossSlam(bossModel: Model, hrp: BasePart, slamRadius: number, slamDamage: number, telegraphDuration: number)
local slamPos = hrp.Position
-- Lingkaran Merah Peringatan
local telegraph = Instance.new("Part")
telegraph.Name = "SlamTelegraph"
telegraph.Shape = Enum.PartType.Cylinder
telegraph.Size = Vector3.new(0.2, 2, 2)
telegraph.CFrame = CFrame.new(slamPos - Vector3.new(0, hrp.Size.Y, 0)) * CFrame.Angles(0, 0, math.rad(90))
telegraph.Anchored = true
telegraph.CanCollide = false
telegraph.Material = Enum.Material.Neon
telegraph.Color = Color3.fromRGB(255, 30, 30)
telegraph.Transparency = 0.5
telegraph.Parent = workspace
-- Efek membesar meluas
local tween = TweenService:Create(telegraph, TweenInfo.new(telegraphDuration, Enum.EasingStyle.Linear), {
Size = Vector3.new(0.2, slamRadius * 2, slamRadius * 2),
Transparency = 0.2
})
tween:Play()
task.wait(telegraphDuration)
telegraph:Destroy()
if not bossModel.Parent or not hrp.Parent then return end
SoundManager.PlaySFX("BatHit", hrp, 1.4)
-- Gelombang kejut tanah
local shockwave = Instance.new("Part")
shockwave.Size = Vector3.new(slamRadius * 2, 1, slamRadius * 2)
shockwave.Position = slamPos - Vector3.new(0, 1.5, 0)
shockwave.Anchored = true
shockwave.CanCollide = false
shockwave.Material = Enum.Material.Neon
shockwave.Color = Color3.fromRGB(255, 100, 30)
shockwave.Transparency = 0.3
shockwave.Parent = workspace
Debris:AddItem(shockwave, 0.4)
-- Beri damage besar dan lempar pemain yang masih berdiri di dalam lingkaran
for _, player in ipairs(Players:GetPlayers()) do
local char = player.Character
local pHrp = char and char:FindFirstChild("HumanoidRootPart") :: BasePart?
if pHrp then
local dist = (pHrp.Position - slamPos).Magnitude
if dist <= slamRadius then
local kbDir = (pHrp.Position - slamPos).Unit * 60 + Vector3.new(0, 30, 0)
CombatService.DamagePlayer(player, slamDamage, kbDir)
end
end
end
end
-- Otak Utama Kecerdasan Buatan (AI) Zombie
local function runZombieAI(model: Model, zType: string)
local zCfg = Config.Zombies[zType]
if not zCfg then return end
local humanoid = model:WaitForChild("Humanoid") :: Humanoid
local hrp = model:WaitForChild("HumanoidRootPart") :: BasePart
-- Pastikan physics zombie dikendalikan 100% oleh server (tidak lag)
for _, part in ipairs(model:GetDescendants()) do
if part:IsA("BasePart") then
part:SetNetworkOwner(nil)
end
end
local lastAttack = 0
local lastSpecialAbility = 0
local isEnraged = false
local isCharging = false
local path = PathfindingService:CreatePath({
AgentRadius = math.clamp(zCfg.SizeScale.X * 1.5, 2, 4),
AgentHeight = math.clamp(zCfg.SizeScale.Y * 4.5, 4, 8),
AgentCanJump = true,
})
local aiLoopRunning = true
local deathConn
deathConn = humanoid.Died:Connect(function()
aiLoopRunning = false
if deathConn then deathConn:Disconnect() end
end)
task.spawn(function()
while aiLoopRunning and model.Parent and humanoid.Health > 0 do
local targetPlayer, targetChar, dist = findClosestPlayer(hrp.Position)
if targetPlayer and targetChar and dist < 300 then
local targetHrp = targetChar:FindFirstChild("HumanoidRootPart") :: BasePart?
if targetHrp then
local now = os.clock()
-- JURUS KHUSUS 1: Spitter Ludah Asam
if zType == "Spitter" and dist <= (zCfg.PreferredRange or 36) and dist >= 10 then
if now - lastSpecialAbility >= (zCfg.RangedCooldown or 3.0) then
lastSpecialAbility = now
humanoid:MoveTo(hrp.Position)
fireAcidProjectile(hrp.Position + Vector3.new(0, 2, 0), targetHrp.Position, zCfg.Damage, zCfg.PuddleDuration, zCfg.PuddleDamage)
task.wait(0.5)
end
end
-- JURUS KHUSUS 2: Boss Abomination (Hentakan Tanah & Serudukan Lari)
if zType == "Abomination" then
if dist <= (zCfg.SlamRadius or 24) and now - lastSpecialAbility >= (zCfg.SlamCooldown or 7.0) then
lastSpecialAbility = now
performBossSlam(model, hrp, zCfg.SlamRadius, zCfg.SlamDamage, zCfg.SlamTelegraphTime)
elseif not isCharging and dist > 18 and dist < 85 and math.random() < 0.35 and now - lastSpecialAbility >= (zCfg.ChargeCooldown or 10.0) then
isCharging = true
lastSpecialAbility = now
humanoid.WalkSpeed = zCfg.ChargeSpeed or 32
task.delay(2.5, function()
if model.Parent and humanoid.Health > 0 then
humanoid.WalkSpeed = zCfg.WalkSpeed
isCharging = false
end
end)
end
-- Cek jika serudukan mengenai pemain
if isCharging and dist <= 7 then
isCharging = false
humanoid.WalkSpeed = zCfg.WalkSpeed
local chargeDmg = zCfg.ChargeDamage or 55
local kbDir = (targetHrp.Position - hrp.Position).Unit * 75 + Vector3.new(0, 25, 0)
CombatService.DamagePlayer(targetPlayer, chargeDmg, kbDir)
SoundManager.PlaySFX("BatHit", hrp, 1.2)
end
end
-- JURUS KHUSUS 3: Boss Final Patient Zero (Slam, Panggil Kroco, Mengamuk)
if zType == "PatientZero" then
-- Mengamuk jika darah tersisa di bawah 40%
if not isEnraged and humanoid.Health <= (humanoid.MaxHealth * (zCfg.EnrageThreshold or 0.4)) then
isEnraged = true
humanoid.WalkSpeed = zCfg.WalkSpeed * 1.35
zCfg.Damage *= 1.35
local highlight = Instance.new("Highlight")
highlight.FillColor = Color3.fromRGB(180, 0, 180)
highlight.OutlineColor = Color3.fromRGB(255, 255, 255)
highlight.Parent = model
SoundManager.PlaySFX("ZombieGroan", hrp, 1.5)
end
-- Boss Slam
if dist <= (zCfg.SlamRadius or 28) and now - lastSpecialAbility >= (zCfg.SlamCooldown or 6.0) then
lastSpecialAbility = now
performBossSlam(model, hrp, zCfg.SlamRadius, zCfg.SlamDamage, zCfg.SlamTelegraphTime)
-- Panggil bantuan zombie Runner
elseif now - lastSpecialAbility >= (zCfg.SummonCooldown or 10.0) then
lastSpecialAbility = now
SoundManager.PlaySFX("ZombieGroan", hrp, 1.0)
for _ = 1, 2 do
local offset = Vector3.new(math.random(-15, 15), 0, math.random(-15, 15))
EnemyService.SpawnEnemy("Runner", CFrame.new(hrp.Position + offset))
end
end
end
-- SERANGAN MELEE DEKAT
if dist <= (zCfg.AttackRange or 5) then
if now - lastAttack >= (zCfg.AttackCooldown or 1.0) then
lastAttack = now
local kbDir: Vector3? = nil
if zType == "Brute" then
kbDir = (targetHrp.Position - hrp.Position).Unit * (zCfg.KnockbackPower or 50) + Vector3.new(0, 18, 0)
end
CombatService.DamagePlayer(targetPlayer, zCfg.Damage, kbDir)
SoundManager.PlaySFX("ZombieGroan", hrp, 0.35)
end
end
-- GERAKAN MENGEJAR PEMAIN (Optimasi Kecepatan Lari)
if isCharging then
humanoid:MoveTo(targetHrp.Position)
else
-- Cek garis lurus (Line of Sight)
local losParams = RaycastParams.new()
losParams.FilterDescendantsInstances = { model, targetChar }
losParams.FilterType = Enum.RaycastFilterType.Exclude
local rayDir = (targetHrp.Position - hrp.Position)
local hitObstacle = workspace:Raycast(hrp.Position, rayDir, losParams)
if not hitObstacle or zType == "Runner" or dist < 25 then
-- Lari langsung secepat mungkin
humanoid:MoveTo(targetHrp.Position)
else
-- Cari jalan memutar mengitari barikade jika terhalang
local success = pcall(function()
path:ComputeAsync(hrp.Position, targetHrp.Position)
end)
if success and path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
if #waypoints >= 2 then
humanoid:MoveTo(waypoints[2].Position)
else
humanoid:MoveTo(targetHrp.Position)
end
else
humanoid:MoveTo(targetHrp.Position)
end
end
end
end
else
humanoid:MoveTo(hrp.Position)
end
-- Responsivitas AI: 0.12 detik untuk Runner agar lari agresif tanpa tersendat!
local stepTime = (zType == "Runner") and 0.12 or 0.25
task.wait(stepTime)
end
end)
end
function EnemyService.SpawnEnemy(typeName: string, spawnCFrame: CFrame): Model?
local template = enemiesFolder:FindFirstChild(typeName)
if not template then
warn("[EnemyService] Template not found for: " .. typeName)
return nil
end
local clone = template:Clone() :: Model
clone:PivotTo(spawnCFrame + Vector3.new(0, 3, 0))
clone.Parent = getZombiesContainer()
local zCfg = Config.Zombies[typeName]
local hum = clone:FindFirstChildOfClass("Humanoid")
if hum and zCfg then
hum.WalkSpeed = zCfg.WalkSpeed
hum.MaxHealth = zCfg.MaxHealth
hum.Health = zCfg.MaxHealth
end
activeZombies[clone] = true
local hrp = clone:FindFirstChild("HumanoidRootPart") or clone.PrimaryPart
if hrp and hrp:IsA("BasePart") then
SoundManager.PlaySFX("ZombieGroan", hrp, 0.45)
end
if zCfg and zCfg.IsBoss then
BossWarning:FireAllClients(zCfg.DisplayName)
if hum then
BossHealthUpdated:FireAllClients(zCfg.DisplayName, hum.Health, hum.MaxHealth)
end
end
runZombieAI(clone, typeName)
clone.Destroying:Connect(function()
activeZombies[clone] = nil
end)
return clone
end
function EnemyService.GetActiveCount(): number
local count = 0
for model in pairs(activeZombies) do
if model and model.Parent then
count += 1
else
activeZombies[model] = nil
end
end
return count
end
function EnemyService.GetActiveZombies(): { Model }
local list = {}
for model in pairs(activeZombies) do
if model and model.Parent then
table.insert(list, model)
else
activeZombies[model] = nil
end
end
return list
end
function EnemyService.ClearAllEnemies()
for model in pairs(activeZombies) do
if model and model.Parent then
model:Destroy()
end
end
table.clear(activeZombies)
local container = workspace:FindFirstChild("Zombies")
if container then
container:ClearAllChildren()
end
for _, child in ipairs(workspace:GetChildren()) do
if child.Name == "AcidPuddle" or child.Name == "AcidSpit" or child.Name == "SlamTelegraph" then
child:Destroy()
end
end
end
return EnemyService
  • Line of Sight Sprint (Kejar Cepat): Sebelum menggunakan Pathfinding yang berat, zombie menembakkan Raycast ke arah pemain. Jika jalanan lurus tanpa rintangan (atau zombie berjenis Runner), zombie langsung lari secepat kilat (28 studs/detik) tanpa tersendat!
  • Spitter (Ludah Asam Beracun): Jika jarak dengan pemain antara 10-36 stud, Spitter akan berhenti sejenak dan menembakkan bola asam lengket neon hijau. Saat bola pecah di tanah, tercipta genangan asam berdurasi 3.5 detik yang melukai siapapun yang menginjaknya.
  • Boss Wave 4 “Abomination”:
    • Hentakan Tanah (Slam): Mengeluarkan lingkaran merah di tanah selama 1.3 detik. Pemain yang tidak sempat menghindar akan terkena 75 damage dan terlempar ke udara!
    • Serudukan Kilat (Ram Charge): Abomination melesat dengan kecepatan 32 stud/detik menabrak pemain dengan gaya tolak 75.
  • Boss Wave 5 “Patient Zero” (Final Boss):
    • Hentakan Raksasa (Slam 95 Damage): Radius 28 stud yang hampir mematikan pemain jika tidak menjaga jarak.
    • Panggilan Kroco (Summon): Setiap 10 detik, Patient Zero memanggil 2 zombie Runner di sekitarnya.
    • Fase Mengamuk (Enrage): Saat HP tersisa < 40%, tubuh boss menyala ungu terang, larinya bertambah cepat 35%, dan damagenya melonjak drastis!