12
This commit is contained in:
1 parent
73e91faa63
commit
e970e0a2e6
11 files changed
+365
-56
No files matched your search
@@ -122,6 +122,17 @@ UserInputService.InputBegan:Connect(function(input, processed)
|
||||
end
|
||||
end)
|
||||
|
||||
-- Сбили зомби — машина теряет долю скорости (сервер считает её по деталям; физику багги ведёт водитель).
|
||||
local impactShake = 0
|
||||
Remotes:WaitForChild("BuggyImpact").OnClientEvent:Connect(function(slow: number)
|
||||
local seat = currentSeat()
|
||||
local chassis = seat and (seat.Parent :: Model).PrimaryPart
|
||||
if chassis and typeof(slow) == "number" then
|
||||
chassis.AssemblyLinearVelocity *= 1 - math.clamp(slow, 0, 0.9)
|
||||
impactShake = math.max(impactShake, slow * 2) -- короткий толчок камеры, сильнее при большом замедлении
|
||||
end
|
||||
end)
|
||||
|
||||
-- ===== Камера за рулём =====
|
||||
-- Держит багги по центру кадра, смотрит чуть сверху. Зажата ПКМ (или палец на экране) — можно осматриваться,
|
||||
-- отпустил — камера плавно возвращается за машину. Колёсико — ближе/дальше. Стены и холмы между машиной
|
||||
@@ -235,6 +246,11 @@ RunService:BindToRenderStep("BuggyCamera", Enum.RenderPriority.Camera.Value + 1,
|
||||
if hit then
|
||||
distance = math.max((hit.Position - target).Magnitude - 1, 3)
|
||||
end
|
||||
camera.CFrame = CFrame.new(target) * rotation * CFrame.new(0, 0, distance)
|
||||
local shake = CFrame.new()
|
||||
if impactShake > 0 then
|
||||
impactShake = math.max(impactShake - dt * 3, 0)
|
||||
shake = CFrame.Angles(math.random(-10, 10) / 400 * impactShake, math.random(-10, 10) / 400 * impactShake, 0)
|
||||
end
|
||||
camera.CFrame = CFrame.new(target) * rotation * CFrame.new(0, 0, distance) * shake
|
||||
camera.Focus = CFrame.new(target)
|
||||
end)
|
||||
@@ -502,6 +502,8 @@ local STAT_ROWS = { { id = "speed", name = "Скорость", color = ORANGE, m
|
||||
for _, stat in G.Stats do
|
||||
table.insert(STAT_ROWS, { id = stat.id, name = stat.name, color = stat.color, max = 100, unit = "" })
|
||||
end
|
||||
-- Пробивная сила: насколько машина сохраняет скорость, сбивая зомби (BuggyStats.RamSlow)
|
||||
table.insert(STAT_ROWS, { id = "ramming", name = "Пробивная сила", color = Color3.fromRGB(235, 165, 40), max = 100, unit = "" })
|
||||
|
||||
local statRows = {}
|
||||
for i, spec in STAT_ROWS do
|
||||
|
||||
@@ -314,7 +314,7 @@ RunService.RenderStepped:Connect(function(dt)
|
||||
heatFill.BackgroundColor3 = overheated and RED or TRACER_COLOR:Lerp(RED, heat)
|
||||
heatLabel.Text = overheated and "ПЕРЕГРЕВ!" or string.upper(item.name) .. " · ЛКМ"
|
||||
|
||||
if firing and not overheated and now - lastShot >= 1 / spec.fireRate then
|
||||
if firing and not overheated and not model:GetAttribute("Locked") and now - lastShot >= 1 / spec.fireRate then
|
||||
lastShot = now
|
||||
heat += spec.heatPerShot
|
||||
if heat >= 1 then
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
-- Отсчёт перед раундом на карте команды: «3, 2, 1» и «НАЧАЛИ!».
|
||||
-- Сервер (Lobby) присылает время старта по серверным часам — у всей команды отсчёт идёт одновременно.
|
||||
|
||||
local Players = game:GetService("Players")
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local RunService = game:GetService("RunService")
|
||||
local TweenService = game:GetService("TweenService")
|
||||
|
||||
local Remotes = ReplicatedStorage:WaitForChild("Remotes")
|
||||
local RoundRemote = Remotes:WaitForChild("RoundStart")
|
||||
|
||||
local player = Players.LocalPlayer
|
||||
|
||||
local ORANGE = Color3.fromRGB(230, 130, 40)
|
||||
local DARK = Color3.fromRGB(30, 14, 6)
|
||||
|
||||
local gui = Instance.new("ScreenGui")
|
||||
gui.Name = "RoundHUD"
|
||||
gui.ResetOnSpawn = false
|
||||
gui.IgnoreGuiInset = true
|
||||
gui.DisplayOrder = 50
|
||||
gui.Enabled = false
|
||||
gui.Parent = player:WaitForChild("PlayerGui")
|
||||
|
||||
-- Вспышка на «НАЧАЛИ!»
|
||||
local flash = Instance.new("Frame")
|
||||
flash.Size = UDim2.fromScale(1, 1)
|
||||
flash.BackgroundColor3 = Color3.fromRGB(255, 220, 160)
|
||||
flash.BackgroundTransparency = 1
|
||||
flash.BorderSizePixel = 0
|
||||
flash.Parent = gui
|
||||
|
||||
local function bigLabel(size: number): (TextLabel, UIScale)
|
||||
local l = Instance.new("TextLabel")
|
||||
l.AnchorPoint = Vector2.new(0.5, 0.5)
|
||||
l.Position = UDim2.fromScale(0.5, 0.42)
|
||||
l.Size = UDim2.fromOffset(900, size * 1.2)
|
||||
l.BackgroundTransparency = 1
|
||||
l.Font = Enum.Font.GothamBlack
|
||||
l.TextSize = size
|
||||
l.TextColor3 = Color3.new(1, 1, 1)
|
||||
l.TextStrokeColor3 = DARK
|
||||
l.TextStrokeTransparency = 0
|
||||
l.TextTransparency = 1
|
||||
l.TextStrokeTransparency = 1
|
||||
l.Parent = gui
|
||||
local s = Instance.new("UIScale")
|
||||
s.Parent = l
|
||||
return l, s
|
||||
end
|
||||
|
||||
local hint, _ = bigLabel(28)
|
||||
hint.Position = UDim2.fromScale(0.5, 0.27)
|
||||
hint.TextColor3 = ORANGE
|
||||
hint.Text = "ПРИГОТОВЬТЕСЬ"
|
||||
|
||||
local number, numberScale = bigLabel(150)
|
||||
|
||||
local go, goScale = bigLabel(170)
|
||||
go.Text = "НАЧАЛИ!"
|
||||
local goGradient = Instance.new("UIGradient")
|
||||
goGradient.Color = ColorSequence.new({
|
||||
ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 235, 90)),
|
||||
ColorSequenceKeypoint.new(0.5, Color3.fromRGB(255, 140, 30)),
|
||||
ColorSequenceKeypoint.new(1, Color3.fromRGB(230, 40, 30)),
|
||||
})
|
||||
goGradient.Rotation = 90
|
||||
goGradient.Parent = go
|
||||
|
||||
local function show(label: TextLabel, visible: boolean, time: number)
|
||||
TweenService:Create(label, TweenInfo.new(time), {
|
||||
TextTransparency = if visible then 0 else 1,
|
||||
TextStrokeTransparency = if visible then 0 else 1,
|
||||
}):Play()
|
||||
end
|
||||
|
||||
-- Цифра «бьёт» по экрану: появляется большой и садится, к концу секунды растворяется.
|
||||
local function popNumber(n: number)
|
||||
number.Text = tostring(n)
|
||||
number.Rotation = 0
|
||||
numberScale.Scale = 1.8
|
||||
number.TextTransparency = 0
|
||||
number.TextStrokeTransparency = 0
|
||||
TweenService:Create(numberScale, TweenInfo.new(0.35, Enum.EasingStyle.Back, Enum.EasingDirection.Out), { Scale = 1 }):Play()
|
||||
task.delay(0.6, function()
|
||||
if number.Text == tostring(n) then
|
||||
show(number, false, 0.3)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
local function popGo()
|
||||
show(number, false, 0.1)
|
||||
show(hint, false, 0.2)
|
||||
goScale.Scale = 0.4
|
||||
go.TextTransparency = 0
|
||||
go.TextStrokeTransparency = 0
|
||||
TweenService:Create(goScale, TweenInfo.new(0.25, Enum.EasingStyle.Back, Enum.EasingDirection.Out), { Scale = 1.15 }):Play()
|
||||
task.delay(0.25, function()
|
||||
TweenService:Create(goScale, TweenInfo.new(0.2), { Scale = 1 }):Play()
|
||||
end)
|
||||
flash.BackgroundTransparency = 0.35
|
||||
TweenService:Create(flash, TweenInfo.new(0.5), { BackgroundTransparency = 1 }):Play()
|
||||
-- Тряска надписи
|
||||
task.spawn(function()
|
||||
for i = 1, 8 do
|
||||
go.Rotation = (if i % 2 == 0 then 1 else -1) * (8 - i) * 0.8
|
||||
go.Position = UDim2.new(0.5, math.random(-6, 6), 0.42, math.random(-4, 4))
|
||||
task.wait(0.035)
|
||||
end
|
||||
go.Rotation = 0
|
||||
go.Position = UDim2.fromScale(0.5, 0.42)
|
||||
end)
|
||||
task.delay(1.2, function()
|
||||
show(go, false, 0.5)
|
||||
task.wait(0.55)
|
||||
gui.Enabled = false
|
||||
end)
|
||||
end
|
||||
|
||||
local countdownId = 0
|
||||
|
||||
RoundRemote.OnClientEvent:Connect(function(startAt: number)
|
||||
countdownId += 1
|
||||
local id = countdownId
|
||||
gui.Enabled = true
|
||||
show(hint, true, 0.3)
|
||||
local shown = nil
|
||||
local connection
|
||||
connection = RunService.RenderStepped:Connect(function()
|
||||
if id ~= countdownId then
|
||||
connection:Disconnect()
|
||||
return
|
||||
end
|
||||
local left = startAt - workspace:GetServerTimeNow()
|
||||
if left > 0 then
|
||||
local n = math.ceil(left)
|
||||
if n ~= shown then
|
||||
shown = n
|
||||
popNumber(n)
|
||||
end
|
||||
else
|
||||
connection:Disconnect()
|
||||
popGo()
|
||||
end
|
||||
end)
|
||||
end)
|
||||
@@ -1,6 +1,7 @@
|
||||
-- Багги апокалипсиса на физике: рама, независимая подвеска на пружинах, полный привод,
|
||||
-- поворотные передние колёса. Управление — с водительского VehicleSeat (WASD).
|
||||
|
||||
local PhysicsService = game:GetService("PhysicsService")
|
||||
local Players = game:GetService("Players")
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local RunService = game:GetService("RunService")
|
||||
@@ -14,6 +15,13 @@ local Buggy = {}
|
||||
|
||||
local active = {} -- [Model] = { seat, chassis, motors, servos }
|
||||
|
||||
-- Группы столкновений: багги и зомби проходят друг сквозь друга, удар считает сервер (Zombies).
|
||||
Buggy.COLLISION_GROUP = "Buggies"
|
||||
Buggy.ZOMBIE_GROUP = "Zombies"
|
||||
PhysicsService:RegisterCollisionGroup(Buggy.COLLISION_GROUP)
|
||||
PhysicsService:RegisterCollisionGroup(Buggy.ZOMBIE_GROUP)
|
||||
PhysicsService:CollisionGroupSetCollidable(Buggy.COLLISION_GROUP, Buggy.ZOMBIE_GROUP, false)
|
||||
|
||||
local RUST = Color3.fromRGB(128, 74, 40)
|
||||
local DARK = Color3.fromRGB(38, 36, 34)
|
||||
local STEEL = Color3.fromRGB(150, 150, 155)
|
||||
@@ -100,7 +108,7 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
|
||||
CFrame = cf,
|
||||
Color = BODY,
|
||||
Material = BODY_MAT,
|
||||
CustomPhysicalProperties = PhysicalProperties.new(1.2, 0.3, 0.2),
|
||||
CustomPhysicalProperties = PhysicalProperties.new(1.2 * B.MassScale, 0.3, 0.2),
|
||||
})
|
||||
model.PrimaryPart = chassis
|
||||
|
||||
@@ -389,8 +397,9 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
|
||||
spring.Attachment1 = slide.Attachment1
|
||||
-- Свободная длина подобрана так, чтобы под весом багги пружина была чуть сжата.
|
||||
spring.FreeLength = SPRING_TOP + 0.8
|
||||
spring.Stiffness = B.SpringStiffness
|
||||
spring.Damping = B.SpringDamping
|
||||
-- Пружины и демпферы растут вместе с массой — подвеска проседает и гасит кочки как раньше.
|
||||
spring.Stiffness = B.SpringStiffness * B.MassScale
|
||||
spring.Damping = B.SpringDamping * B.MassScale
|
||||
spring.Parent = hub
|
||||
|
||||
local axleParent = hub
|
||||
@@ -420,7 +429,7 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
|
||||
Material = Enum.Material.Fabric,
|
||||
-- Под гусеницами колесо невидимое и цепляется сильнее.
|
||||
Transparency = if wheelSpec.tracks then 1 else 0,
|
||||
CustomPhysicalProperties = PhysicalProperties.new(0.8, if wheelSpec.tracks then 2 else 1.6, 0.1, 100, 1),
|
||||
CustomPhysicalProperties = PhysicalProperties.new(0.8 * B.MassScale, if wheelSpec.tracks then 2 else 1.6, 0.1, 100, 1),
|
||||
})
|
||||
local rim = newPart(model, "Part", {
|
||||
Name = w.name .. "Rim",
|
||||
@@ -459,7 +468,7 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
|
||||
motor.Attachment0 = attachment(axleParent, CFrame.new(), "Axle")
|
||||
motor.Attachment1 = attachment(wheel, CFrame.new(), "Axle")
|
||||
motor.ActuatorType = Enum.ActuatorType.Motor
|
||||
motor.MotorMaxTorque = B.CoastTorque
|
||||
motor.MotorMaxTorque = B.CoastTorque * B.MassScale
|
||||
motor.Parent = wheel
|
||||
table.insert(motors, motor)
|
||||
end
|
||||
@@ -537,6 +546,9 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
|
||||
for _, d in model:GetDescendants() do
|
||||
if d:IsA("BasePart") then
|
||||
d.Anchored = false
|
||||
-- С зомби багги физически не сталкивается (не наезжает на них колесом и не переворачивается):
|
||||
-- удар считает сервер (Zombies), а машина теряет немного скорости.
|
||||
d.CollisionGroup = Buggy.COLLISION_GROUP
|
||||
end
|
||||
end
|
||||
|
||||
@@ -547,13 +559,33 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
|
||||
servos = servos,
|
||||
wheelRadius = R,
|
||||
speedFactor = Buggy.SpeedFactor(setup),
|
||||
ramSlow = BuggyStats.RamSlow(setup), -- доля скорости, теряемая при ударе о зомби
|
||||
owner = owner,
|
||||
throttle = 0,
|
||||
-- spec — параметры пушки из слота «Оружие» (Config.Garage.Parts → gun)
|
||||
gun = { motor = gunMotor, spec = weaponItem.gun, heat = 0, heatTime = os.clock(), lastShot = 0, overheated = false },
|
||||
locked = false,
|
||||
}
|
||||
if options.locked then
|
||||
Buggy.SetLocked(model, true) -- на карте команды — до старта раунда
|
||||
end
|
||||
return model
|
||||
end
|
||||
|
||||
-- Тормоз до старта раунда: не едет и не стреляет (атрибут Locked видит и клиент).
|
||||
function Buggy.SetLocked(model: Model, locked: boolean)
|
||||
local data = active[model]
|
||||
if data then
|
||||
data.locked = locked
|
||||
model:SetAttribute("Locked", locked)
|
||||
end
|
||||
end
|
||||
|
||||
-- Все багги в игре: [Model] = данные.
|
||||
function Buggy.All()
|
||||
return active
|
||||
end
|
||||
|
||||
function Buggy.Get(model: Model)
|
||||
return active[model]
|
||||
end
|
||||
@@ -616,8 +648,9 @@ function Buggy.Start()
|
||||
active[model] = nil
|
||||
continue
|
||||
end
|
||||
local input = data.seat.ThrottleFloat
|
||||
local steer = data.seat.SteerFloat
|
||||
-- До старта раунда (locked) машина стоит на тормозе и не слушается руля.
|
||||
local input = if data.locked then 0 else data.seat.ThrottleFloat
|
||||
local steer = if data.locked then 0 else data.seat.SteerFloat
|
||||
data.throttle = approach(data.throttle, input, dt)
|
||||
|
||||
-- Целевая скорость колёс (studs/с). Только поворот без газа — медленно ползём вперёд.
|
||||
@@ -636,7 +669,8 @@ function Buggy.Start()
|
||||
|
||||
-- Вперёд — это -Z рамы, поэтому колёса крутим в отрицательную сторону вокруг оси X.
|
||||
local angular = -speed / data.wheelRadius * B.DriveSign
|
||||
local torque = if driving then B.MotorTorque else B.CoastTorque
|
||||
-- Тяга растёт вместе с массой — разгон как у лёгкой машины.
|
||||
local torque = (if driving or data.locked then B.MotorTorque else B.CoastTorque) * B.MassScale
|
||||
for _, motor in data.motors do
|
||||
motor.AngularVelocity = angular
|
||||
motor.MotorMaxTorque = torque
|
||||
|
||||
@@ -357,9 +357,15 @@ function Garage.RemoveBuggy(player: Player)
|
||||
end
|
||||
end
|
||||
|
||||
function Garage.BuggyOf(player: Player): Model?
|
||||
local state = states[player]
|
||||
return state and state.buggy
|
||||
end
|
||||
|
||||
-- Ставит личную багги игрока в точку ground (смотрит по -Z) и сажает его за руль.
|
||||
-- loadingText — подпись на экране загрузки, пока подгружается место.
|
||||
function Garage.SpawnBuggy(player: Player, ground: CFrame, loadingText: string)
|
||||
-- loadingText — подпись на экране загрузки, пока подгружается место; locked — на тормозе до старта раунда.
|
||||
-- Возвращается, когда загрузка у игрока прошла.
|
||||
function Garage.SpawnBuggy(player: Player, ground: CFrame, loadingText: string, locked: boolean?)
|
||||
local state = states[player]
|
||||
local character = player.Character
|
||||
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
|
||||
@@ -369,7 +375,7 @@ function Garage.SpawnBuggy(player: Player, ground: CFrame, loadingText: string)
|
||||
if state.buggy then
|
||||
Buggy.Destroy(state.buggy)
|
||||
end
|
||||
state.buggy = Buggy.Build(ground, { setup = state.setup, owner = player })
|
||||
state.buggy = Buggy.Build(ground, { setup = state.setup, owner = player, locked = locked })
|
||||
local seat = state.buggy:FindFirstChild("DriverSeat") :: VehicleSeat
|
||||
if not teleport(player, seat.CFrame * CFrame.new(0, 3, 0), loadingText) then
|
||||
return
|
||||
|
||||
@@ -11,6 +11,7 @@ local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local Config = require(ReplicatedStorage.Shared.Config)
|
||||
local Garage = require(script.Parent.Garage)
|
||||
local Hangar = require(script.Parent.Hangar)
|
||||
local Buggy = require(script.Parent.Buggy)
|
||||
local World = require(script.Parent.World)
|
||||
local Zombies = require(script.Parent.Zombies)
|
||||
|
||||
@@ -24,6 +25,7 @@ local DARK = Color3.fromRGB(38, 36, 34)
|
||||
-- owner — создатель, members — все в лобби (создатель первый), arena — [Player] = true, кто сейчас на карте.
|
||||
-- token меняется при каждом изменении состава — так отменяется устаревший отсчёт.
|
||||
local circles = {}
|
||||
local RoundRemote: RemoteEvent -- отсчёт перед раундом: клиенту приходит время старта (Round.client)
|
||||
local lastAction = {} -- [Player] = os.clock()
|
||||
|
||||
local function part(parent: Instance, props): BasePart
|
||||
@@ -137,20 +139,56 @@ local function publish(circle)
|
||||
end
|
||||
end
|
||||
|
||||
-- Начало раунда: ждём, пока у всей команды пройдёт загрузка (багги пока на тормозе), появляются зомби,
|
||||
-- отсчёт у всех игроков (RoundStart) — и на «НАЧАЛИ!» тормоз отпускается, зомби идут в атаку.
|
||||
local function startRound(index: number, team: { Player })
|
||||
local start = workspace:GetServerTimeNow() + Config.Zombies.Countdown
|
||||
local playing = {}
|
||||
for _, player in team do
|
||||
if player.Parent and player:GetAttribute("Arena") == index then
|
||||
table.insert(playing, player)
|
||||
RoundRemote:FireClient(player, start)
|
||||
end
|
||||
end
|
||||
if #playing == 0 then
|
||||
return -- команда уже ушла
|
||||
end
|
||||
Zombies.Start(index)
|
||||
task.wait(Config.Zombies.Countdown)
|
||||
for _, player in playing do
|
||||
local buggy = Garage.BuggyOf(player)
|
||||
if buggy then
|
||||
Buggy.SetLocked(buggy, false)
|
||||
end
|
||||
end
|
||||
Zombies.Attack(index)
|
||||
end
|
||||
|
||||
local function launch(circle)
|
||||
local team = circle.members
|
||||
circle.members, circle.owner, circle.size = {}, nil, 0
|
||||
circle.token += 1
|
||||
circle.status = "playing"
|
||||
local loading = #team
|
||||
for k, player in team do
|
||||
player:SetAttribute("Lobby", 0)
|
||||
player:SetAttribute("Arena", circle.index)
|
||||
circle.arena[player] = true
|
||||
-- Параллельно: у каждого свой экран загрузки, никто не ждёт соседа.
|
||||
task.spawn(Garage.SpawnBuggy, player, World.ArenaSpawn(circle.index, k, #team), "Карта команды " .. circle.index)
|
||||
task.spawn(function()
|
||||
Garage.SpawnBuggy(player, World.ArenaSpawn(circle.index, k, #team), "Карта команды " .. circle.index, true)
|
||||
loading -= 1
|
||||
end)
|
||||
end
|
||||
Zombies.Start(circle.index)
|
||||
publish(circle)
|
||||
|
||||
-- Ждём загрузку всей команды (не дольше 30 секунд — вдруг у кого-то завис интернет).
|
||||
local deadline = os.clock() + 30
|
||||
while loading > 0 and os.clock() < deadline do
|
||||
task.wait(0.2)
|
||||
end
|
||||
task.wait(1) -- у последнего ещё гаснет заставка
|
||||
startRound(circle.index, team)
|
||||
end
|
||||
|
||||
-- После любого изменения состава или размера: заполнилось — запускаем отсчёт, освободилось место — отменяем.
|
||||
@@ -331,6 +369,10 @@ function Lobby.Init(remotes: Folder)
|
||||
publish(circles[index])
|
||||
end
|
||||
|
||||
RoundRemote = Instance.new("RemoteEvent")
|
||||
RoundRemote.Name = "RoundStart"
|
||||
RoundRemote.Parent = remotes
|
||||
|
||||
local ActionRemote = Instance.new("RemoteEvent")
|
||||
ActionRemote.Name = "LobbyAction"
|
||||
ActionRemote.Parent = remotes
|
||||
|
||||
@@ -158,6 +158,9 @@ function Weapons.Init(remotes: Folder)
|
||||
return
|
||||
end
|
||||
local data = Buggy.Get(model)
|
||||
if data.locked then
|
||||
return -- раунд ещё не начался
|
||||
end
|
||||
local gun = data.gun
|
||||
local spec = gun.spec
|
||||
local now = os.clock()
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
-- Зомби на картах команд. Когда команда выехала (Lobby → Zombies.Start), на карте держится стая:
|
||||
-- новые приходят из-за пределов видимости вокруг игроков, бегут к ближайшему и бьют вблизи.
|
||||
-- Урон им наносят пули и взрывы (Weapons) и таран багги (здесь). Каждое попадание сервер сообщает клиентам
|
||||
-- Зомби на картах команд. Когда команда загрузилась (Lobby → Zombies.Start), вокруг появляется стая и ждёт;
|
||||
-- на «НАЧАЛИ!» (Zombies.Attack) бросается в атаку. Новые приходят из-за пределов видимости вокруг игроков,
|
||||
-- бегут к ближайшему и бьют вблизи.
|
||||
-- Урон им наносят пули и взрывы (Weapons) и таран багги (здесь): физически багги сквозь зомби не наезжает,
|
||||
-- удар считаем сами — зомби отлетает, машина чуть теряет скорость (меньше с тараном, бронёй, гусеницами). Каждое попадание сервер сообщает клиентам
|
||||
-- (ZombieHit) — они рисуют вылетающие цифры урона и искры. Убившему — осколки.
|
||||
-- Команда покинула карту (Lobby → Zombies.Stop) — зомби убираются.
|
||||
|
||||
local Debris = game:GetService("Debris")
|
||||
local Players = game:GetService("Players")
|
||||
local ReplicatedStorage = game:GetService("ReplicatedStorage")
|
||||
local RunService = game:GetService("RunService")
|
||||
|
||||
local Config = require(ReplicatedStorage.Shared.Config)
|
||||
local Buggy = require(script.Parent.Buggy)
|
||||
@@ -26,6 +29,7 @@ local template: Model? = nil
|
||||
-- [номер карты] = { index, folder, zombies = { [Model] = data }, started }
|
||||
local arenas = {}
|
||||
local HitRemote: RemoteEvent
|
||||
local ImpactRemote: RemoteEvent -- водителю: сбить скорость после удара о зомби
|
||||
|
||||
-- ===== Модель =====
|
||||
|
||||
@@ -49,6 +53,8 @@ local function makeTemplate(): Model?
|
||||
for _, d in model:GetDescendants() do
|
||||
if d:IsA("BaseScript") then
|
||||
d:Destroy() -- стандартная анимация игрока не нужна
|
||||
elseif d:IsA("BasePart") then
|
||||
d.CollisionGroup = Buggy.ZOMBIE_GROUP -- сквозь багги, удар считает checkRams
|
||||
end
|
||||
end
|
||||
local humanoid = model:FindFirstChildOfClass("Humanoid") :: Humanoid
|
||||
@@ -147,29 +153,56 @@ local function onDeath(arena, model: Model, data)
|
||||
Debris:AddItem(model, 3)
|
||||
end
|
||||
|
||||
-- Багги на скорости сбивает зомби: урон от скорости, детали спереди добавляют. Зомби отлетает.
|
||||
local function onTouched(data, part: BasePart)
|
||||
if data.humanoid.Health <= 0 then
|
||||
return
|
||||
end
|
||||
local buggyModel = part:FindFirstAncestorOfClass("Model")
|
||||
local buggy = buggyModel and Buggy.Get(buggyModel)
|
||||
if not buggy then
|
||||
return
|
||||
end
|
||||
-- Багги и зомби физически друг сквозь друга (группы столкновений в Buggy) — иначе зомби попадает под колесо,
|
||||
-- как на трамплин, и машину переворачивает. Удар считаем сами: зомби внутри габаритов багги.
|
||||
local function insideBuggy(chassis: BasePart, position: Vector3): boolean
|
||||
local p = chassis.CFrame:PointToObjectSpace(position)
|
||||
return math.abs(p.X) < 4.8 and p.Z > -8.5 and p.Z < 6.5 and p.Y > -4 and p.Y < 5
|
||||
end
|
||||
|
||||
-- Багги на скорости сбивает зомби: урон от скорости, детали спереди добавляют, зомби отлетает,
|
||||
-- машина теряет немного скорости (сколько — зависит от деталей, BuggyStats.RamSlow).
|
||||
-- Медленно наехал — зомби просто отталкивает в сторону.
|
||||
local function ram(data, buggyModel: Model, buggy)
|
||||
local now = os.clock()
|
||||
local speed = (buggy.chassis.AssemblyLinearVelocity - data.root.AssemblyLinearVelocity).Magnitude
|
||||
if speed < Z.RamSpeed or now - data.lastRam < 0.4 then
|
||||
if now - data.lastRam < 0.4 then
|
||||
return
|
||||
end
|
||||
data.lastRam = now
|
||||
local chassis = buggy.chassis
|
||||
local speed = (chassis.AssemblyLinearVelocity - data.root.AssemblyLinearVelocity).Magnitude
|
||||
if speed < Z.RamSpeed then
|
||||
local side = chassis.CFrame.RightVector * (if chassis.CFrame:PointToObjectSpace(data.root.Position).X >= 0 then 1 else -1)
|
||||
data.root.AssemblyLinearVelocity = side * 14 + Vector3.new(0, 6, 0)
|
||||
return
|
||||
end
|
||||
local driver = Buggy.Driver(buggyModel)
|
||||
if driver then
|
||||
data.humanoid:SetAttribute("LastHitBy", driver.UserId)
|
||||
-- Машину считает водитель — замедление применяет его клиент (Driving.client)
|
||||
ImpactRemote:FireClient(driver, buggy.ramSlow)
|
||||
end
|
||||
local bonus = FRONT_BONUS[buggyModel:GetAttribute("Front") or ""] or 1
|
||||
data.humanoid:TakeDamage((10 + (speed - Z.RamSpeed) * Z.RamDamage) * bonus)
|
||||
data.root.AssemblyLinearVelocity = buggy.chassis.AssemblyLinearVelocity * 1.1 + Vector3.new(0, 25, 0)
|
||||
data.root.AssemblyLinearVelocity = chassis.AssemblyLinearVelocity * 1.1 + Vector3.new(0, 25, 0)
|
||||
end
|
||||
|
||||
-- Каждый кадр: какие зомби оказались внутри какой-нибудь багги.
|
||||
local function checkRams()
|
||||
for _, arena in arenas do
|
||||
for _, data in arena.zombies do
|
||||
if data.humanoid.Health <= 0 then
|
||||
continue
|
||||
end
|
||||
local position = data.root.Position
|
||||
for buggyModel, buggy in Buggy.All() do
|
||||
if buggy.chassis.Parent and (buggy.chassis.Position - position).Magnitude < 12 and insideBuggy(buggy.chassis, position) then
|
||||
ram(data, buggyModel, buggy)
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function spawnZombie(arena, targets)
|
||||
@@ -215,14 +248,6 @@ local function spawnZombie(arena, targets)
|
||||
humanoid.Died:Connect(function()
|
||||
onDeath(arena, model, data)
|
||||
end)
|
||||
for _, name in { "HumanoidRootPart", "Torso" } do
|
||||
local part = model:FindFirstChild(name) :: BasePart?
|
||||
if part then
|
||||
part.Touched:Connect(function(other)
|
||||
onTouched(data, other)
|
||||
end)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ===== ИИ =====
|
||||
@@ -254,7 +279,13 @@ local function think(arena)
|
||||
model:Destroy()
|
||||
continue
|
||||
end
|
||||
if nearest then
|
||||
if nearest and not arena.attacking then
|
||||
-- Раунд ещё не начался: стоят и смотрят на ближайшего игрока.
|
||||
data.humanoid:MoveTo(data.root.Position)
|
||||
if data.walk and data.walk.IsPlaying then
|
||||
data.walk:Stop()
|
||||
end
|
||||
elseif nearest then
|
||||
-- Вне видимости бредут медленнее, заметив — бегут.
|
||||
data.humanoid.WalkSpeed = data.speed * (if distance <= Z.SightRange then 1 else 0.6)
|
||||
data.humanoid:MoveTo(nearest.root.Position)
|
||||
@@ -290,16 +321,21 @@ end
|
||||
|
||||
-- ===== Карты =====
|
||||
|
||||
-- Стая появляется вокруг команды и ждёт (Lobby запускает это на отсчёте перед раундом).
|
||||
function Zombies.Start(index: number)
|
||||
Zombies.Stop(index)
|
||||
local folder = Instance.new("Folder")
|
||||
folder.Name = "Zombies" .. index
|
||||
folder.Parent = workspace
|
||||
local arena = { index = index, folder = folder, zombies = {}, started = false, pending = 0 }
|
||||
arenas[index] = arena
|
||||
task.delay(Z.StartDelay, function()
|
||||
arena.started = true
|
||||
end)
|
||||
arenas[index] = { index = index, folder = folder, zombies = {}, started = true, attacking = false, pending = 0 }
|
||||
end
|
||||
|
||||
-- Раунд начался — в атаку.
|
||||
function Zombies.Attack(index: number)
|
||||
local arena = arenas[index]
|
||||
if arena then
|
||||
arena.attacking = true
|
||||
end
|
||||
end
|
||||
|
||||
function Zombies.Stop(index: number)
|
||||
@@ -314,9 +350,13 @@ function Zombies.Init(remotes: Folder)
|
||||
HitRemote = Instance.new("RemoteEvent")
|
||||
HitRemote.Name = "ZombieHit"
|
||||
HitRemote.Parent = remotes
|
||||
ImpactRemote = Instance.new("RemoteEvent")
|
||||
ImpactRemote.Name = "BuggyImpact"
|
||||
ImpactRemote.Parent = remotes
|
||||
task.spawn(function()
|
||||
template = makeTemplate()
|
||||
end)
|
||||
RunService.Heartbeat:Connect(checkRams)
|
||||
task.spawn(function()
|
||||
while true do
|
||||
task.wait(THINK_INTERVAL)
|
||||
|
||||
@@ -23,9 +23,21 @@ function BuggyStats.SpeedFactor(setup): number
|
||||
return factor
|
||||
end
|
||||
|
||||
-- { speed = км/ч, [id характеристики] = 0..100 } для Config.Garage.Stats.
|
||||
-- Какую долю скорости багги теряет при ударе о зомби: Config.Zombies.RamSlow, ослабленная деталями с impact.
|
||||
function BuggyStats.RamSlow(setup): number
|
||||
local slow = Config.Zombies.RamSlow
|
||||
eachPart(setup, function(item)
|
||||
slow *= 1 - (item.impact or 0)
|
||||
end)
|
||||
return slow
|
||||
end
|
||||
|
||||
-- { speed = км/ч, ramming = 0..100 (пробивная сила), [id характеристики] = 0..100 } для Config.Garage.Stats.
|
||||
function BuggyStats.Compute(setup)
|
||||
local result = { speed = Config.Buggy.MaxSpeed * BuggyStats.SpeedFactor(setup) }
|
||||
local result = {
|
||||
speed = Config.Buggy.MaxSpeed * BuggyStats.SpeedFactor(setup),
|
||||
ramming = (1 - BuggyStats.RamSlow(setup) / Config.Zombies.RamSlow) * 100,
|
||||
}
|
||||
for _, stat in Config.Garage.Stats do
|
||||
local value = stat.base
|
||||
eachPart(setup, function(item)
|
||||
|
||||
@@ -20,6 +20,9 @@ Config.Buggy = {
|
||||
-- Если на W багги едет назад или руль перепутан — поменяйте знак на -1.
|
||||
DriveSign = 1,
|
||||
SteerSign = 1,
|
||||
-- Во сколько раз багги тяжелее «обычной»: тяга, пружины и демпферы умножаются на это же, поэтому
|
||||
-- машина едет как раньше, но её не раскачивают взрывы и кочки.
|
||||
MassScale = 4,
|
||||
AutoFlipTime = 5, -- через столько секунд на боку или на крыше багги сама встаёт на колёса
|
||||
AutoFlipTilt = 0.35, -- «перевёрнута», если верх рамы смотрит вверх меньше чем на столько (косинус наклона)
|
||||
}
|
||||
@@ -94,23 +97,24 @@ Config.Garage = {
|
||||
-- fireRate — выстрелов в секунду, damage — урон (у снарядов — в центре взрыва), spread — разброс в градусах,
|
||||
-- heatPerShot — нагрев за выстрел (1 — перегрев), blastRadius — радиус взрыва, speed — скорость снаряда.
|
||||
-- stats — вклад в характеристики (см. Stats ниже): offroad, durability, handling, firepower.
|
||||
-- impact — пробивная сила (0–1): насколько деталь гасит замедление от удара о зомби (Config.Zombies.RamSlow).
|
||||
Parts = {
|
||||
{ id = "spikes", slot = "front", name = "Шипы", icon = "🔺", info = "Шипованный бампер", starter = true,
|
||||
stats = { durability = 5, firepower = 5 } },
|
||||
stats = { durability = 5, firepower = 5 }, impact = 0.3 },
|
||||
{ id = "ram", slot = "front", name = "Таран", icon = "🧱", info = "Наклонный отвал из листа железа", starter = true,
|
||||
stats = { durability = 15, handling = -5 } },
|
||||
stats = { durability = 15, handling = -5 }, impact = 0.6 },
|
||||
{ id = "bucket", slot = "front", name = "Ковш", icon = "⛏️", info = "Ковш с зубьями — сгребает всё на пути (−5% скорости)", price = 150, speed = 0.95,
|
||||
stats = { durability = 10, offroad = 10, handling = -10 } },
|
||||
stats = { durability = 10, offroad = 10, handling = -10 }, impact = 0.7 },
|
||||
{ id = "bayonets", slot = "front", name = "Штыки", icon = "🗡️", info = "Длинные штыки вперёд", price = 200,
|
||||
stats = { firepower = 12 } },
|
||||
stats = { firepower = 12 }, impact = 0.4 },
|
||||
{ id = "wheels_std", slot = "wheels", name = "Стандарт", icon = "⚙️", info = "Обычные колёса", radius = 1.7, width = 1.3, starter = true,
|
||||
stats = { offroad = 15, handling = 15 } },
|
||||
{ id = "wheels_big", slot = "wheels", name = "Внедорожные", icon = "🚙", info = "Большие колёса, высокий клиренс", radius = 2.1, width = 1.6, price = 120,
|
||||
stats = { offroad = 40 } },
|
||||
stats = { offroad = 40 }, impact = 0.15 },
|
||||
{ id = "wheels_low", slot = "wheels", name = "Низкие", icon = "⭕", info = "Маленькие колёса, низкая посадка", radius = 1.45, width = 1.15, starter = true,
|
||||
stats = { offroad = -5, handling = 30 } },
|
||||
{ id = "tracks", slot = "wheels", name = "Гусеницы", icon = "⛓️", info = "Цепкие, но медленнее (−20% скорости)", radius = 1.7, width = 1.7, tracks = true, speed = 0.8, price = 300,
|
||||
stats = { offroad = 60, durability = 10, handling = -15 } },
|
||||
stats = { offroad = 60, durability = 10, handling = -15 }, impact = 0.35 },
|
||||
{ id = "grille", slot = "rear", name = "Решётка", icon = "🔳", info = "Защитная решётка над мотором", starter = true,
|
||||
stats = { durability = 8 } },
|
||||
{ id = "hood", slot = "rear", name = "Бронекрышка", icon = "🛡️", info = "Бронированное перекрытие кормы", armor = true, price = 180,
|
||||
@@ -118,9 +122,9 @@ Config.Garage = {
|
||||
{ id = "cans", slot = "rear", name = "Канистры", icon = "🛢️", info = "Багажник с канистрами", starter = true,
|
||||
stats = { offroad = 5, durability = -5 } },
|
||||
{ id = "armor_light", slot = "armor", name = "Лёгкая броня", icon = "🔰", info = "Бронелисты на бортах (−5% скорости)", armor = true, speed = 0.95, price = 150,
|
||||
stats = { durability = 25, handling = -5 } },
|
||||
stats = { durability = 25, handling = -5 }, impact = 0.2 },
|
||||
{ id = "armor_heavy", slot = "armor", name = "Тяжёлая броня", icon = "🏰", info = "Борта и бронещиток спереди (−15% скорости)", armor = true, speed = 0.85, price = 350,
|
||||
stats = { durability = 50, handling = -15 } },
|
||||
stats = { durability = 50, handling = -15 }, impact = 0.45 },
|
||||
{ id = "mg_light", slot = "weapon", name = "Лёгкий автомат", icon = "🔫", info = "Слабый, зато долго не перегревается", starter = true,
|
||||
gun = { kind = "bullet", fireRate = 10, damage = 6, spread = 1, heatPerShot = 0.035 }, stats = { firepower = 25 } },
|
||||
{ id = "mg_heavy", slot = "weapon", name = "Тяжёлый автомат", icon = "💥", info = "Крупный калибр: бьёт сильно и точно", price = 250,
|
||||
@@ -144,7 +148,7 @@ Config.Garage = {
|
||||
|
||||
-- Зомби на картах команд: появляются, когда команда выехала, бегут к ближайшему игроку и бьют вблизи.
|
||||
Config.Zombies = {
|
||||
StartDelay = 6, -- секунд после старта: игроки успевают пройти заставку загрузки
|
||||
Countdown = 3, -- отсчёт перед раундом, когда вся команда загрузилась; потом «НАЧАЛИ!» и зомби в атаку
|
||||
Base = 8, -- сколько зомби одновременно на карте
|
||||
PerPlayer = 4, -- и ещё столько на каждого игрока команды
|
||||
Max = 30,
|
||||
@@ -158,6 +162,9 @@ Config.Zombies = {
|
||||
AttackCooldown = 1.1,
|
||||
RamSpeed = 14, -- с какой скорости багги сбивает зомби
|
||||
RamDamage = 2.2, -- урон тараном = (скорость − RamSpeed) × это, детали спереди добавляют сверху
|
||||
-- Доля скорости, которую голая багги теряет при ударе о зомби. Каждая деталь с impact гасит часть:
|
||||
-- итог = RamSlow × (1 − impact₁) × (1 − impact₂) × … — с тараном, бронёй и гусеницами почти ноль.
|
||||
RamSlow = 0.25,
|
||||
ShardsPerKill = 2, -- награда убившему
|
||||
Color = Color3.fromRGB(105, 135, 85),
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user