This commit is contained in:
Leshyi committed 2026-11-02 18:23:44 +03:00
1 parent cf12c5a430
commit ce8f6c3409
19 files changed
+52871 -164

No files matched your search

File diff suppressed because it is too large. Load diff
Binary file not shown.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+14
View File
@@ -0,0 +1,14 @@
newmtl Part1Mtl
Material Color
Ka 1 1 0
Kd 1 1 0
Ks 0.0784314 0.0784314 0
d 1
Ns 22
map_Ka Part1_diff.png
map_Kd Part1_diff.png
map_d Part1_diff.png
+27067
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+69 -7
View File
@@ -1,5 +1,6 @@
-- Туман у края карты: на карте лёгкая дымка, чем ближе камера к границе, тем гуще атмосфера,
-- у края и за ним не видно ничего. Издалека край и небо над картой закрывают туманные слои (World.buildEdge).
-- Туман: в ангаре лёгкая дымка, в бою на карте команды — густой туман (атмосфера плотнее и стелющиеся
-- по земле клубы вокруг камеры). Чем ближе камера к границе карты, тем гуще, у края и за ним не видно ничего.
-- Издалека край и небо над картой закрывают туманные слои (World.buildEdge).
-- Камеру не пускаем за край карты и выше туманного потолка — сразу после того, как её поставил модуль камеры.
-- Карты квадратные (Config.World.Size), центры в ряд по X через Config.Lobby.MapSpacing, Z = 0.
-- Гаражи далеко за картами — там ничего не трогаем.
@@ -19,6 +20,12 @@ local FOG_RANGE = 260 -- за сколько studs до края туман на
local EDGE_DENSITY = 0.97
local EDGE_HAZE = 10
local EDGE_OFFSET = 0.9
-- Густой туман в бою: видно примерно на 150–200 studs, зомби выходят прямо из тумана.
local BATTLE_DENSITY = 0.62
local BATTLE_HAZE = 3.5
local BATTLE_OFFSET = 0.3
local GROUND_FOG_RADIUS = 38 -- клубы у земли — кольцом вокруг камеры
local GROUND_FOG_PUFFS = 8
local CAMERA_MARGIN = 4 -- насколько камера может подойти к краю карты
local CAMERA_TOP = CEILING - 20 -- выше камера не поднимается, туман над ней
@@ -68,7 +75,37 @@ RunService:BindToRenderStep("KeepCameraInZone", Enum.RenderPriority.Camera.Value
end
end)
local factor = 0
-- Стелющиеся клубы у земли: невидимые точки кольцом вокруг камеры с медленным серым дымом.
local groundFog = Instance.new("Folder")
groundFog.Name = "GroundFog"
groundFog.Parent = workspace
local puffs = {}
for i = 1, GROUND_FOG_PUFFS do
local p = Instance.new("Part")
p.Anchored = true
p.CanCollide = false
p.CanQuery = false
p.CanTouch = false
p.Transparency = 1
p.Size = Vector3.new(1, 1, 1)
p.Parent = groundFog
local smoke = Instance.new("Smoke")
smoke.Color = Color3.fromRGB(150, 150, 153)
smoke.Size = 32
smoke.RiseVelocity = 0.6
smoke.Opacity = 0
smoke.Enabled = false
smoke.Parent = p
puffs[i] = { part = p, smoke = smoke, angle = (i - 1) / GROUND_FOG_PUFFS * math.pi * 2 }
end
local groundParams = RaycastParams.new()
groundParams.FilterType = Enum.RaycastFilterType.Include
groundParams.FilterDescendantsInstances = { workspace.Terrain }
local groundY = 0
local lastGroundCheck = 0
local factor, battle = 0, 0
RunService.RenderStepped:Connect(function(dt)
if not atmosphere or not atmosphere.Parent then
atmosphere = Lighting:FindFirstChildOfClass("Atmosphere")
@@ -79,10 +116,35 @@ RunService.RenderStepped:Connect(function(dt)
baseDensity, baseHaze, baseOffset = atmosphere.Density, atmosphere.Haze, atmosphere.Offset
factor = 0
end
local target = edgeFactor(workspace.CurrentCamera.CFrame.Position)
local cameraPosition = workspace.CurrentCamera.CFrame.Position
local target = edgeFactor(cameraPosition)
factor += (target - factor) * math.min(dt * 3, 1) -- плавно, без скачков при телепорте
-- Бой: игрок на карте команды и камера над этой картой
local inBattle = (Players.LocalPlayer:GetAttribute("Arena") or 0) > 0 and mapCenter(cameraPosition) ~= nil
battle += ((if inBattle then 1 else 0) - battle) * math.min(dt * 1.5, 1)
-- Сначала обычный туман или туман боя, поверх — сгущение у края
local density = baseDensity + (BATTLE_DENSITY - baseDensity) * battle
local haze = baseHaze + (BATTLE_HAZE - baseHaze) * battle
local offset = baseOffset + (BATTLE_OFFSET - baseOffset) * battle
local t = factor ^ 1.3
atmosphere.Density = baseDensity + (EDGE_DENSITY - baseDensity) * t
atmosphere.Haze = baseHaze + (EDGE_HAZE - baseHaze) * t
atmosphere.Offset = baseOffset + (EDGE_OFFSET - baseOffset) * t
atmosphere.Density = density + (EDGE_DENSITY - density) * t
atmosphere.Haze = haze + (EDGE_HAZE - haze) * t
atmosphere.Offset = offset + (EDGE_OFFSET - offset) * t
-- Клубы у земли видны только в бою
local visible = battle > 0.05
if visible and os.clock() - lastGroundCheck > 0.4 then
lastGroundCheck = os.clock()
local hit = workspace:Raycast(cameraPosition + Vector3.new(0, 5, 0), Vector3.new(0, -200, 0), groundParams)
groundY = if hit then hit.Position.Y else cameraPosition.Y - 8
end
for _, puff in puffs do
puff.smoke.Enabled = visible
if visible then
puff.smoke.Opacity = 0.09 * battle
local a = puff.angle + os.clock() * 0.03 -- кольцо медленно поворачивается — дымка «ползёт»
puff.part.Position = Vector3.new(cameraPosition.X + math.cos(a) * GROUND_FOG_RADIUS, groundY + 1, cameraPosition.Z + math.sin(a) * GROUND_FOG_RADIUS)
end
end
end)
+372
View File
@@ -0,0 +1,372 @@
-- Сцена победы (после босса последней волны, VictoryStart от Lobby). Команда стоит в линию на тормозе.
-- «ПОБЕДА!» с золотом, лучами и конфетти; камера мягко отрывается от машины и облетает строй по дуге спереди;
-- справа выезжает таблица итогов (места, убитые зомби, заработанные осколки, кто добил босса),
-- внизу — карточка своего результата со счётчиками. Потом сервер возвращает всех в ангар.
local Lighting = game:GetService("Lighting")
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 player = Players.LocalPlayer
local rng = Random.new()
local GOLD = Color3.fromRGB(255, 205, 70)
local GOLD_DEEP = Color3.fromRGB(235, 130, 30)
local TEXT = Color3.fromRGB(245, 235, 220)
local MUTED = Color3.fromRGB(190, 170, 150)
local BG = Color3.fromRGB(26, 19, 14)
local GREEN = Color3.fromRGB(110, 220, 100)
local SHARD = Color3.fromRGB(120, 210, 230)
local DEFAULT_FOV = 70
local BAR = 0.1
local gui = Instance.new("ScreenGui")
gui.Name = "VictoryHUD"
gui.ResetOnSpawn = false
gui.IgnoreGuiInset = true
gui.DisplayOrder = 900
gui.Enabled = false
gui.Parent = player:WaitForChild("PlayerGui")
local function frame(parent: Instance, props): Frame
local f = Instance.new("Frame")
f.BorderSizePixel = 0
for k, v in props do
f[k] = v
end
f.Parent = parent
return f
end
local function label(parent: Instance, props): TextLabel
local l = Instance.new("TextLabel")
l.BackgroundTransparency = 1
l.Font = Enum.Font.GothamBlack
l.TextColor3 = TEXT
l.TextStrokeColor3 = Color3.fromRGB(15, 8, 3)
l.TextStrokeTransparency = 0.3
for k, v in props do
l[k] = v
end
l.Parent = parent
return l
end
local function tween(object: Instance, time: number, goal, style: Enum.EasingStyle?, direction: Enum.EasingDirection?)
local t = TweenService:Create(object, TweenInfo.new(time, style or Enum.EasingStyle.Quad, direction or Enum.EasingDirection.Out), goal)
t:Play()
return t
end
local function smooth(t: number): number
return t * t * (3 - 2 * t)
end
-- ===== Сцена =====
local scene: Frame? = nil
local effects = {}
local hidden = {}
local function cleanup()
RunService:UnbindFromRenderStep("VictoryCamera")
workspace.CurrentCamera.FieldOfView = DEFAULT_FOV
for _, effect in effects do
effect:Destroy()
end
effects = {}
for _, other in hidden do
other.Enabled = true
end
hidden = {}
if scene then
scene:Destroy()
scene = nil
end
gui.Enabled = false
end
-- Конфетти: цветные кусочки падают сверху, кувыркаясь
local function confetti(parent: Instance, count: number)
local colors = { GOLD, GOLD_DEEP, Color3.fromRGB(255, 80, 70), GREEN, Color3.fromRGB(90, 170, 255), Color3.fromRGB(230, 110, 230) }
for i = 1, count do
task.delay(rng:NextNumber(0, 1.6), function()
if not parent.Parent then
return
end
local piece = frame(parent, {
AnchorPoint = Vector2.new(0.5, 0.5),
Position = UDim2.new(rng:NextNumber(0, 1), 0, -0.05, 0),
Size = UDim2.fromOffset(rng:NextInteger(6, 12), rng:NextInteger(10, 18)),
BackgroundColor3 = colors[rng:NextInteger(1, #colors)],
Rotation = rng:NextNumber(0, 360),
ZIndex = 5,
})
local fall = rng:NextNumber(2.8, 4.5)
tween(piece, fall, {
Position = UDim2.new(piece.Position.X.Scale + rng:NextNumber(-0.12, 0.12), 0, 1.05, 0),
Rotation = piece.Rotation + rng:NextNumber(-720, 720),
}, Enum.EasingStyle.Sine, Enum.EasingDirection.In)
task.delay(fall, function()
piece:Destroy()
end)
end)
end
end
-- «ПОБЕДА!» с золотым градиентом, лучами за надписью и тряской
local function bigTitle(parent: Instance)
local holder = frame(parent, { AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.3), Size = UDim2.fromOffset(10, 10), BackgroundTransparency = 1 })
local rays = frame(holder, { AnchorPoint = Vector2.new(0.5, 0.5), Position = UDim2.fromScale(0.5, 0.5), Size = UDim2.fromOffset(10, 10), BackgroundTransparency = 1 })
for i = 0, 11 do
frame(rays, {
AnchorPoint = Vector2.new(0.5, 0.5),
Position = UDim2.fromScale(0.5, 0.5),
Size = UDim2.fromOffset(900, if i % 2 == 0 then 26 else 14),
Rotation = i * 15,
BackgroundColor3 = GOLD,
BackgroundTransparency = 0.82,
})
end
task.spawn(function()
while rays.Parent do
rays.Rotation += 0.4
task.wait()
end
end)
local title = label(holder, {
AnchorPoint = Vector2.new(0.5, 0.5),
Position = UDim2.fromScale(0.5, 0.5),
Size = UDim2.fromOffset(1100, 170),
TextSize = 150,
TextColor3 = Color3.new(1, 1, 1),
TextStrokeTransparency = 0,
Text = "ПОБЕДА!",
})
local gradient = Instance.new("UIGradient")
gradient.Color = ColorSequence.new({
ColorSequenceKeypoint.new(0, Color3.fromRGB(255, 245, 170)),
ColorSequenceKeypoint.new(0.5, GOLD),
ColorSequenceKeypoint.new(1, GOLD_DEEP),
})
gradient.Rotation = 90
gradient.Parent = title
local scale = Instance.new("UIScale", holder)
scale.Scale = 0.2
tween(scale, 0.45, { Scale = 1.1 }, Enum.EasingStyle.Back)
task.delay(0.45, function()
tween(scale, 0.25, { Scale = 1 })
end)
task.spawn(function()
for i = 1, 12 do
title.Rotation = (if i % 2 == 0 then 1 else -1) * (12 - i) * 0.6
task.wait(0.035)
end
title.Rotation = 0
end)
-- Через пару секунд надпись уменьшается и уходит вверх, освобождая место итогам
task.delay(2.6, function()
if holder.Parent then
tween(holder, 0.6, { Position = UDim2.fromScale(0.5, 0.17) }, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)
tween(scale, 0.6, { Scale = 0.55 }, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut)
end
end)
end
-- Таблица итогов справа: строки выезжают по очереди
local function resultsTable(parent: Instance, results)
local panel = frame(parent, {
AnchorPoint = Vector2.new(1, 0.5),
Position = UDim2.new(1, 460, 0.52, 0),
Size = UDim2.fromOffset(440, 70 + #results * 58),
BackgroundColor3 = BG,
BackgroundTransparency = 0.12,
})
Instance.new("UICorner", panel).CornerRadius = UDim.new(0, 14)
local stroke = Instance.new("UIStroke", panel)
stroke.Color = GOLD_DEEP
stroke.Thickness = 2
label(panel, { Position = UDim2.fromOffset(20, 12), Size = UDim2.fromOffset(400, 34), TextSize = 26, TextColor3 = GOLD, TextXAlignment = Enum.TextXAlignment.Left, Text = "ИТОГИ БОЯ" })
label(panel, { Position = UDim2.fromOffset(250, 18), Size = UDim2.fromOffset(170, 24), TextSize = 14, TextColor3 = MUTED, Font = Enum.Font.GothamBold, TextXAlignment = Enum.TextXAlignment.Right, Text = "🧟 зомби 💎 осколки" })
tween(panel, 0.6, { Position = UDim2.new(1, -40, 0.52, 0) }, Enum.EasingStyle.Back)
local medals = { "🥇", "🥈", "🥉" }
for i, result in results do
local own = result.userId == player.UserId
local row = frame(panel, {
Position = UDim2.fromOffset(460, 58 + (i - 1) * 58),
Size = UDim2.fromOffset(410, 50),
BackgroundColor3 = if own then Color3.fromRGB(40, 60, 32) else Color3.fromRGB(44, 34, 26),
})
Instance.new("UICorner", row).CornerRadius = UDim.new(0, 10)
if own then
local s = Instance.new("UIStroke", row)
s.Color = GREEN
s.Thickness = 2
end
label(row, { Position = UDim2.fromOffset(8, 0), Size = UDim2.fromOffset(40, 50), TextSize = 26, Text = medals[i] or (i .. "."), TextStrokeTransparency = 1 })
label(row, {
Position = UDim2.fromOffset(52, 0),
Size = UDim2.fromOffset(190, 50),
TextSize = 18,
TextXAlignment = Enum.TextXAlignment.Left,
TextTruncate = Enum.TextTruncate.AtEnd,
TextColor3 = if own then GREEN else TEXT,
Text = result.name .. (if result.boss then " 💀" else ""),
})
label(row, { Position = UDim2.fromOffset(242, 0), Size = UDim2.fromOffset(70, 50), TextSize = 20, Text = tostring(result.kills) })
label(row, { Position = UDim2.fromOffset(318, 0), Size = UDim2.fromOffset(84, 50), TextSize = 20, TextColor3 = SHARD, Text = "+" .. result.shards })
task.delay(0.5 + i * 0.25, function()
tween(row, 0.45, { Position = UDim2.fromOffset(15, 58 + (i - 1) * 58) }, Enum.EasingStyle.Back)
end)
end
label(panel, {
AnchorPoint = Vector2.new(0, 1),
Position = UDim2.new(0, 20, 1, -6),
Size = UDim2.fromOffset(400, 16),
TextSize = 12,
Font = Enum.Font.GothamMedium,
TextColor3 = MUTED,
TextXAlignment = Enum.TextXAlignment.Left,
Text = "💀 — добил босса",
})
end
-- Счётчик: число прокручивается от 0 до value
local function countUp(l: TextLabel, value: number, format: string, time: number)
local started = os.clock()
task.spawn(function()
while l.Parent do
local t = math.clamp((os.clock() - started) / time, 0, 1)
l.Text = format:format(math.floor(value * smooth(t) + 0.5))
if t >= 1 then
break
end
task.wait()
end
end)
end
-- Карточка своего результата внизу по центру
local function personalCard(parent: Instance, mine, bonus: number)
local card = frame(parent, {
AnchorPoint = Vector2.new(0.5, 1),
Position = UDim2.new(0.5, 0, 1.3, 0),
Size = UDim2.fromOffset(560, 120),
BackgroundColor3 = BG,
BackgroundTransparency = 0.08,
})
Instance.new("UICorner", card).CornerRadius = UDim.new(0, 16)
local stroke = Instance.new("UIStroke", card)
stroke.Color = GREEN
stroke.Thickness = 2
label(card, { Position = UDim2.fromOffset(0, 8), Size = UDim2.new(1, 0, 0, 24), TextSize = 18, TextColor3 = GREEN, Text = "ТВОЙ РЕЗУЛЬТАТ" })
local kills = label(card, { Position = UDim2.fromOffset(20, 36), Size = UDim2.new(0.5, -20, 0, 50), TextSize = 36, Text = "🧟 0" })
local shards = label(card, { Position = UDim2.new(0.5, 0, 0, 36), Size = UDim2.new(0.5, -20, 0, 50), TextSize = 36, TextColor3 = SHARD, Text = "💎 +0" })
label(card, { Position = UDim2.fromOffset(0, 88), Size = UDim2.new(1, 0, 0, 22), TextSize = 14, Font = Enum.Font.GothamBold, TextColor3 = MUTED, Text = ("зомби убито · осколков заработано (в т. ч. +%d за победу)"):format(bonus) })
tween(card, 0.6, { Position = UDim2.new(0.5, 0, 1 - BAR, -16) }, Enum.EasingStyle.Back)
task.delay(0.5, function()
countUp(kills, mine and mine.kills or 0, "🧟 %d", 1.4)
countUp(shards, mine and mine.shards or 0, "💎 +%d", 1.8)
end)
end
-- ===== Камера =====
local function startCamera(buggies: { Model }, startedAt: number, duration: number)
local camera = workspace.CurrentCamera
local center, count = Vector3.zero, 0
for _, model in buggies do
if model and model.PrimaryPart then
center += model.PrimaryPart.Position
count += 1
end
end
if count == 0 then
return
end
center /= count
local radius = math.max(26, count * 10 + 14)
local fromCF = camera.CFrame
local fromFov = camera.FieldOfView
RunService:BindToRenderStep("VictoryCamera", Enum.RenderPriority.Camera.Value + 3, function()
local elapsed = workspace:GetServerTimeNow() - startedAt
local u = math.clamp(elapsed / (duration * 0.9), 0, 1)
-- Дуга перед строем (машины смотрят на -Z): слева направо, ниже в середине, выше по краям
local a = math.rad(-65 + 130 * smooth(u))
local height = 5 + 7 * math.cos(math.pi * u) ^ 2
local position = center + Vector3.new(math.sin(a) * radius, height, -math.cos(a) * radius)
local target = CFrame.lookAt(position, center + Vector3.new(0, 2, 0)) * CFrame.Angles(0, 0, math.rad(math.sin(u * math.pi * 2) * 2))
-- Первые полторы секунды мягко отрываемся от камеры за рулём
local blend = smooth(math.clamp(elapsed / 1.5, 0, 1))
camera.CFrame = fromCF:Lerp(target, blend)
camera.FieldOfView = fromFov + (52 - fromFov) * blend
if effects.dof then
effects.dof.FocusDistance = (camera.CFrame.Position - center).Magnitude
end
end)
end
-- ===== Начало сцены =====
Remotes:WaitForChild("VictoryStart").OnClientEvent:Connect(function(results, buggies: { Model }, startedAt: number, duration: number, bonus: number)
cleanup()
gui.Enabled = true
-- Прячем остальной интерфейс
for _, other in player.PlayerGui:GetChildren() do
if other:IsA("ScreenGui") and other ~= gui and other.Enabled and other.Name ~= "LoadingScreen" then
other.Enabled = false
table.insert(hidden, other)
end
end
local dof = Instance.new("DepthOfFieldEffect")
dof.FarIntensity = 0.35
dof.NearIntensity = 0.2
dof.InFocusRadius = 22
dof.Parent = Lighting
local grade = Instance.new("ColorCorrectionEffect")
grade.Contrast = 0.1
grade.Saturation = 0.15
grade.TintColor = Color3.fromRGB(255, 245, 225)
grade.Parent = Lighting
effects = { dof = dof, grade = grade }
local root = frame(gui, { Size = UDim2.fromScale(1, 1), BackgroundTransparency = 1 })
scene = root
local topBar = frame(root, { Size = UDim2.fromScale(1, BAR), Position = UDim2.fromScale(0, -BAR), BackgroundColor3 = Color3.new(0, 0, 0) })
local bottomBar = frame(root, { Size = UDim2.fromScale(1, BAR), Position = UDim2.fromScale(0, 1), BackgroundColor3 = Color3.new(0, 0, 0) })
tween(topBar, 0.6, { Position = UDim2.fromScale(0, 0) })
tween(bottomBar, 0.6, { Position = UDim2.fromScale(0, 1 - BAR) })
local flash = frame(root, { Size = UDim2.fromScale(1, 1), BackgroundColor3 = GOLD, BackgroundTransparency = 0.4 })
tween(flash, 0.6, { BackgroundTransparency = 1 })
bigTitle(root)
confetti(root, 110)
startCamera(buggies, startedAt, duration)
local mine = nil
for _, result in results do
if result.userId == player.UserId then
mine = result
end
end
task.delay(2.8, function()
if scene == root then
resultsTable(root, results)
personalCard(root, mine, bonus)
confetti(root, 50)
end
end)
-- Конец: сервер переносит в ангар (с заставкой загрузки) — убираем сцену чуть раньше
task.delay(duration - 0.3, function()
if scene == root then
cleanup()
end
end)
end)
+197 -115
View File
@@ -1,5 +1,7 @@
-- Багги апокалипсиса на физике: рама, независимая подвеска на пружинах, полный привод,
-- поворотные передние колёса. Управление — с водительского VehicleSeat (WASD).
-- Внешний вид — модель из тулбокса (Config.Buggy.Model): корпус — меш, приваренный к раме,
-- колёса — меши на наших физических колёсах (крутятся и поворачивают вместе с ними).
local PhysicsService = game:GetService("PhysicsService")
local Players = game:GetService("Players")
@@ -25,21 +27,42 @@ PhysicsService:CollisionGroupSetCollidable(Buggy.COLLISION_GROUP, Buggy.ZOMBIE_G
local RUST = Color3.fromRGB(128, 74, 40)
local DARK = Color3.fromRGB(38, 36, 34)
local STEEL = Color3.fromRGB(150, 150, 155)
local TIRE = Color3.fromRGB(24, 24, 24)
local WHEEL_Y = -1.3 -- центр колеса относительно рамы
local SPRING_TOP = 2 -- крепление пружины над центром колеса
-- Ось вложения (его X) смотрит вверх: для подвески и поворота руля.
local VERTICAL = CFrame.fromMatrix(Vector3.zero, Vector3.yAxis, Vector3.zAxis)
-- Модель: корпус смотрит вперёд по −X меша, ось колёс — Z меша; у нас вперёд −Z, ось колёс — X.
local MODEL = B.Model
local S = MODEL.Scale
local BODY_TURN = CFrame.fromMatrix(Vector3.zero, Vector3.zAxis, Vector3.yAxis, Vector3.new(-1, 0, 0))
-- Колёса: колпак меша смотрит в +Z меша — у правых колёс наружу (+X), у левых разворачиваем.
local MESH_TURN = CFrame.fromMatrix(Vector3.zero, Vector3.new(0, 0, -1), Vector3.yAxis, Vector3.xAxis)
local MESH_TURN_LEFT = CFrame.Angles(0, math.pi, 0) * MESH_TURN
-- Колёса там же, где в модели; центр рамы — над центром корпуса.
local WHEELS = {
{ name = "FL", x = -3.9, z = -3.4, steer = true },
{ name = "FR", x = 3.9, z = -3.4, steer = true },
{ name = "RL", x = -3.9, z = 3.6, steer = false },
{ name = "RR", x = 3.9, z = 3.6, steer = false },
{ name = "FL", side = -1, axle = MODEL.FrontWheel, steer = true },
{ name = "FR", side = 1, axle = MODEL.FrontWheel, steer = true },
{ name = "RL", side = -1, axle = MODEL.RearWheel, steer = false },
{ name = "RR", side = 1, axle = MODEL.RearWheel, steer = false },
}
local WHEELBASE = 7 -- расстояние между осями, для радиуса поворота
for _, w in WHEELS do
w.x = w.side * w.axle.side * S
w.z = -w.axle.forward * S
end
local WHEELBASE = (MODEL.FrontWheel.forward - MODEL.RearWheel.forward) * S -- для радиуса поворота
local FRONT_Z = -MODEL.Body.size.X / 2 * S -- нос и корма корпуса
local REAR_Z = MODEL.Body.size.X / 2 * S
-- Детали из гаража собраны вокруг старой, более короткой рамы — сдвигаем их к носу и корме корпуса.
local FRONT_OFFSET = CFrame.new(0, -0.6, -2.3)
local REAR_OFFSET = CFrame.new(0, -0.9, 2.6)
-- Невидимая рама: столкновения машины примерно по габаритам корпуса; плотность подобрана под прежнюю массу.
local CHASSIS_SIZE = Vector3.new(6.6, 1.6, 13)
local CHASSIS_DENSITY = 1.2 * 60 / (CHASSIS_SIZE.X * CHASSIS_SIZE.Y * CHASSIS_SIZE.Z)
local function newPart(model: Model, className: string, props): BasePart
local p = Instance.new(className)
@@ -93,23 +116,30 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
local front, rear, armor = setup.front or "", setup.rear or "", setup.armor or ""
local weaponItem = Config.PartById[setup.weapon or ""] or Config.PartById.mg_light
local weapon = weaponItem.id
local R, WIDTH = wheelSpec.radius, wheelSpec.width
local BODY, BODY_MAT = paint.color, paint.material or Enum.Material.Metal
local FRAME, FRAME_MAT = accent.color, accent.material or Enum.Material.Metal
-- Колёса из гаража: крупнее или мельче стандартных (радиус 1.7) — так же меняются колёса модели
local wheelScale = wheelSpec.radius / 1.7
local widthScale = wheelSpec.width / 1.3
local function wheelRadius(axle): number
return axle.radius * S * wheelScale
end
-- Большие колёса поднимают машину
local ride = MODEL.RideHeight + (wheelRadius(MODEL.RearWheel) - MODEL.RearWheel.radius * S)
local WIDTH = 1.3 * widthScale
local model = Instance.new("Model")
model.Name = if options.display then "Display" else "ApocalypseBuggy"
model:SetAttribute("Weapon", weapon) -- по нему клиент берёт темп, нагрев и вид выстрела
model:SetAttribute("Front", front) -- детали спереди усиливают таран по зомби (Zombies)
local cf = groundCFrame * CFrame.new(0, R - WHEEL_Y + 0.3, 0)
local cf = groundCFrame * CFrame.new(0, ride, 0)
local chassis = newPart(model, "Part", {
Name = "Chassis",
Size = Vector3.new(6, 1, 10),
Size = CHASSIS_SIZE,
CFrame = cf,
Color = BODY,
Material = BODY_MAT,
CustomPhysicalProperties = PhysicalProperties.new(1.2 * B.MassScale, 0.3, 0.2),
Transparency = 1, -- видно корпус-меш
CustomPhysicalProperties = PhysicalProperties.new(CHASSIS_DENSITY * B.MassScale, 0.3, 0.2),
})
model.PrimaryPart = chassis
@@ -122,43 +152,59 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
weld(chassis, p)
return p
end
-- Тот же декор, но со сдвигом всех деталей на base (к носу или корме корпуса).
local function shifted(base: CFrame)
return function(props, className: string?)
props.CFrame = base * props.CFrame
return deco(props, className)
end
end
-- Водительское место
-- Меш модели на детали-носителе (SpecialMesh: текстуру можно подкрасить цветом из гаража).
local function meshPart(parent: Model, name: string, spec, cframe: CFrame, scale: Vector3, tint: Color3?): BasePart
local p = newPart(parent, "Part", {
Name = name,
Size = spec.size * scale,
CFrame = cframe,
CanCollide = false,
CanQuery = false, -- пули ловят рама и водитель, а не габарит меша
CanTouch = false,
Massless = true,
})
local mesh = Instance.new("SpecialMesh")
mesh.MeshType = Enum.MeshType.FileMesh
mesh.MeshId = spec.mesh
mesh.TextureId = spec.texture
mesh.Scale = scale
if tint then
mesh.VertexColor = Vector3.new(tint.R, tint.G, tint.B)
end
mesh.Parent = p
return p
end
-- Корпус модели (покраска из гаража слегка окрашивает текстуру)
local tint = Color3.new(1, 1, 1):Lerp(BODY, MODEL.Tint)
local body = meshPart(model, "Body", MODEL.Body, cf * CFrame.new(0, MODEL.Body.ground * S - ride, 0) * BODY_TURN, Vector3.one * S, tint)
weld(chassis, body)
-- Водительское место: одно, по центру кабины, как в исходной модели
local seat = newPart(model, "VehicleSeat", {
Name = "DriverSeat",
Size = Vector3.new(2, 0.8, 2),
CFrame = cf * CFrame.new(0, 0.9, 1),
Color = DARK,
Material = Enum.Material.Fabric,
Size = Vector3.new(2, 0.4, 2),
CFrame = cf * CFrame.new(0, 2.2 - ride, 1.7),
Transparency = 1,
Massless = true,
HeadsUpDisplay = false,
MaxSpeed = 0,
})
weld(chassis, seat)
deco({ Size = Vector3.new(2, 2.4, 0.4), CFrame = CFrame.new(0, 2.2, 2.1), Color = DARK, Material = Enum.Material.Fabric })
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.2, 1.3, 1.3), CFrame = CFrame.new(0, 2.3, -0.3) * CFrame.Angles(0, math.pi / 2, 0) * CFrame.Angles(0, 0, math.rad(-25)), Color = DARK })
-- Каркас безопасности
for _, x in { -2.7, 2.7 } do
for _, z in { -1.2, 3 } do
deco({ Size = Vector3.new(0.35, 4, 0.35), CFrame = CFrame.new(x, 2.5, z), Color = FRAME, Material = FRAME_MAT })
end
deco({ Size = Vector3.new(0.35, 0.35, 4.6), CFrame = CFrame.new(x, 4.5, 0.9), Color = FRAME, Material = FRAME_MAT })
deco({ Size = Vector3.new(0.3, 0.3, 4.6), CFrame = CFrame.new(x, 2.5, 0.9) * CFrame.Angles(math.rad(42), 0, 0), Color = FRAME, Material = FRAME_MAT })
end
for _, z in { -1.2, 3 } do
deco({ Size = Vector3.new(5.75, 0.35, 0.35), CFrame = CFrame.new(0, 4.5, z), Color = FRAME, Material = FRAME_MAT })
end
deco({ Size = Vector3.new(5.4, 0.15, 3.8), CFrame = CFrame.new(0, 4.75, 0.9), Color = BODY, Material = BODY_MAT })
-- Капот
deco({ Size = Vector3.new(5, 1, 3.4), CFrame = CFrame.new(0, 1, -3.4) * CFrame.Angles(math.rad(-8), 0, 0), Color = BODY, Material = BODY_MAT })
-- ===== Детали из слотов гаража (Config.Garage.Parts) =====
-- Бронелист: попадание в него не достаётся водителю (см. Weapons).
local ARMOR = STEEL:Lerp(DARK, 0.5)
local function armorPlate(props)
local function armorPlateAt(props)
props.Color = props.Color or ARMOR
props.Material = props.Material or Enum.Material.DiamondPlate
local p = deco(props)
@@ -166,7 +212,10 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
return p
end
-- Перед
-- Перед (собран под старую раму — сдвигаем к носу корпуса)
local frontDeco = shifted(FRONT_OFFSET)
do
local deco = frontDeco
if front == "spikes" then
deco({ Size = Vector3.new(6.6, 0.9, 0.8), CFrame = CFrame.new(0, 0.1, -5.3), Color = DARK, Material = Enum.Material.Metal })
for x = -2.6, 2.6, 1.3 do
@@ -204,8 +253,15 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
deco({ Size = Vector3.new(0.14, 0.45, 0.9), CFrame = blade * CFrame.new(0, 0, -4.45), Color = STEEL, Material = Enum.Material.Metal }, "WedgePart")
end
end
end
-- Зад (мотор — коробка 4×1.8×2.4 с центром в (0, 1.4, 3.9), выхлопные трубы по бокам)
-- Зад (собран под старую раму — сдвигаем к корме корпуса)
do
local deco = shifted(REAR_OFFSET)
local function armorPlate(props)
props.CFrame = REAR_OFFSET * props.CFrame
return armorPlateAt(props)
end
if rear == "grille" then
for _, z in { 2.8, 3.9, 5 } do
deco({ Size = Vector3.new(4.4, 0.18, 0.18), CFrame = CFrame.new(0, 2.9, z), Color = FRAME, Material = FRAME_MAT })
@@ -224,58 +280,65 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
armorPlate({ Size = Vector3.new(0.3, 1.7, 3.4), CFrame = CFrame.new(x, 2.2, 4.1) })
end
elseif rear == "cans" then
-- Канистры по бортам за каркасом и пара на крыше
for _, x in { -3.05, 3.05 } do
for i, z in { 3.6, 4.6 } do
deco({ Size = Vector3.new(0.5, 1.3, 0.85), CFrame = CFrame.new(x, 2.4, z), Color = if i == 1 then Color3.fromRGB(150, 35, 28) else Color3.fromRGB(80, 95, 50), Material = Enum.Material.Metal })
-- Ряд канистр поперёк кормы на стойке
for i, x in { -1.8, -0.6, 0.6, 1.8 } do
deco({ Size = Vector3.new(0.85, 1.3, 0.5), CFrame = CFrame.new(x, 1.8, 5.3), Color = if i % 2 == 1 then Color3.fromRGB(150, 35, 28) else Color3.fromRGB(80, 95, 50), Material = Enum.Material.Metal })
end
deco({ Size = Vector3.new(0.15, 0.15, 2.2), CFrame = CFrame.new(x, 2.6, 4.1), Color = DARK, Material = Enum.Material.Metal })
end
for _, x in { -1, 1 } do
deco({ Size = Vector3.new(0.85, 0.5, 1.3), CFrame = CFrame.new(x, 5.08, 1.4), Color = Color3.fromRGB(150, 35, 28), Material = Enum.Material.Metal })
deco({ Size = Vector3.new(4.4, 0.15, 0.15), CFrame = CFrame.new(0, 2.2, 5.6), Color = DARK, Material = Enum.Material.Metal })
end
end
-- Броня
-- Броня: бронелисты вплотную вокруг кабины (по её бортам, на длину сиденья) — мимо колёс и гусениц.
-- Кабина модели ≈ 4.8 в ширину, сиденье — на 1.7 позади центра рамы.
local CABIN_X = 2.45 -- борт кабины от середины
local CABIN_FRONT, CABIN_BACK = -1.2, 3.9 -- щиток перед ногами водителя и лист за спинкой
local CABIN_Z, CABIN_LEN = (CABIN_FRONT + CABIN_BACK) / 2, CABIN_BACK - CABIN_FRONT
if armor == "armor_light" then
for _, x in { -2.95, 2.95 } do
armorPlate({ Size = Vector3.new(0.25, 1.5, 4.4), CFrame = CFrame.new(x, 1.2, 0.9) })
deco({ Size = Vector3.new(0.3, 0.15, 4.4), CFrame = CFrame.new(x, 2, 0.9), Color = DARK, Material = Enum.Material.Metal })
for _, x in { -CABIN_X, CABIN_X } do
armorPlateAt({ Size = Vector3.new(0.25, 1.5, CABIN_LEN), CFrame = CFrame.new(x, 0.4, CABIN_Z) })
deco({ Size = Vector3.new(0.3, 0.15, CABIN_LEN), CFrame = CFrame.new(x, 1.2, CABIN_Z), Color = DARK, Material = Enum.Material.Metal })
end
elseif armor == "armor_heavy" then
for _, x in { -2.95, 2.95 } do
armorPlate({ Size = Vector3.new(0.35, 2.6, 5), CFrame = CFrame.new(x, 1.7, 0.9) })
deco({ Size = Vector3.new(0.4, 0.15, 5), CFrame = CFrame.new(x, 3.05, 0.9), Color = DARK, Material = Enum.Material.Metal })
for _, x in { -CABIN_X, CABIN_X } do
armorPlateAt({ Size = Vector3.new(0.35, 2.4, CABIN_LEN), CFrame = CFrame.new(x, 0.8, CABIN_Z) })
deco({ Size = Vector3.new(0.4, 0.15, CABIN_LEN), CFrame = CFrame.new(x, 2.05, CABIN_Z), Color = DARK, Material = Enum.Material.Metal })
end
-- Бронещиток перед водителем со смотровой щелью
armorPlate({ Size = Vector3.new(5.2, 1, 0.25), CFrame = CFrame.new(0, 2.3, -1.45) })
armorPlate({ Size = Vector3.new(5.2, 0.7, 0.25), CFrame = CFrame.new(0, 3.65, -1.45) })
-- Бронещиток перед водителем со смотровой щелью на уровне глаз
local width = CABIN_X * 2 + 0.35
armorPlateAt({ Size = Vector3.new(width, 1, 0.25), CFrame = CFrame.new(0, 1.6, CABIN_FRONT) })
armorPlateAt({ Size = Vector3.new(width, 0.7, 0.25), CFrame = CFrame.new(0, 2.95, CABIN_FRONT) })
-- Лист за спинкой сиденья
armorPlateAt({ Size = Vector3.new(width, 2.4, 0.25), CFrame = CFrame.new(0, 0.8, CABIN_BACK) })
end
-- Гусеницы: ленты вокруг колёс по бортам, сами колёса (физика) прячем ниже.
-- Гусеницы: ленты вокруг колёс по бортам, сами колёса (и их меши) прячем ниже.
if wheelSpec.tracks then
local TRACK = Color3.fromRGB(30, 30, 30)
local zf, zr = WHEELS[1].z, WHEELS[3].z
local mid, len = (zf + zr) / 2, zr - zf
for _, x in { -3.9, 3.9 } do
deco({ Size = Vector3.new(WIDTH, 0.35, len), CFrame = CFrame.new(x, WHEEL_Y + R - 0.15, mid), Color = TRACK, Material = Enum.Material.Fabric })
deco({ Size = Vector3.new(WIDTH, 0.35, len), CFrame = CFrame.new(x, WHEEL_Y - R + 0.2, mid), Color = TRACK, Material = Enum.Material.Fabric })
local R = (wheelRadius(MODEL.FrontWheel) + wheelRadius(MODEL.RearWheel)) / 2
local Y = R - ride -- центр колёс относительно рамы
for _, side in { -1, 1 } do
local x = side * (MODEL.FrontWheel.side + MODEL.RearWheel.side) / 2 * S
deco({ Size = Vector3.new(WIDTH, 0.35, len), CFrame = CFrame.new(x, Y + R - 0.15, mid), Color = TRACK, Material = Enum.Material.Fabric })
deco({ Size = Vector3.new(WIDTH, 0.35, len), CFrame = CFrame.new(x, Y - R + 0.2, mid), Color = TRACK, Material = Enum.Material.Fabric })
for _, z in { zf, zr } do
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(WIDTH, R * 2 - 0.05, R * 2 - 0.05), CFrame = CFrame.new(x, WHEEL_Y, z), Color = TRACK, Material = Enum.Material.Fabric })
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(WIDTH + 0.1, R * 1.1, R * 1.1), CFrame = CFrame.new(x, WHEEL_Y, z), Color = FRAME, Material = FRAME_MAT })
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(WIDTH, R * 2 - 0.05, R * 2 - 0.05), CFrame = CFrame.new(x, Y, z), Color = TRACK, Material = Enum.Material.Fabric })
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(WIDTH + 0.1, R * 1.1, R * 1.1), CFrame = CFrame.new(x, Y, z), Color = FRAME, Material = FRAME_MAT })
end
-- Опорные катки и грунтозацепы
for _, z in { -1.6, 0.1, 1.8 } do
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(WIDTH + 0.1, R * 0.9, R * 0.9), CFrame = CFrame.new(x, WHEEL_Y - R * 0.45, z), Color = DARK, Material = Enum.Material.Metal })
for k = 1, 3 do
local z = zf + len * k / 4
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(WIDTH + 0.1, R * 0.9, R * 0.9), CFrame = CFrame.new(x, Y - R * 0.45, z), Color = DARK, Material = Enum.Material.Metal })
end
for z = zf, zr, 0.7 do
deco({ Size = Vector3.new(WIDTH + 0.05, 0.12, 0.3), CFrame = CFrame.new(x, WHEEL_Y + R + 0.08, z), Color = Color3.fromRGB(55, 55, 55), Material = Enum.Material.Metal })
end
deco({ Size = Vector3.new(WIDTH + 0.4, 0.2, len + R * 2 + 0.6), CFrame = CFrame.new(x, WHEEL_Y + R + 0.45, mid), Color = BODY, Material = BODY_MAT })
deco({ Size = Vector3.new(WIDTH + 0.05, 0.12, 0.3), CFrame = CFrame.new(x, Y + R + 0.08, z), Color = Color3.fromRGB(55, 55, 55), Material = Enum.Material.Metal })
end
end
for _, x in { -1.8, 1.8 } do
local lamp = deco({ Size = Vector3.new(0.9, 0.7, 0.3), CFrame = CFrame.new(x, 1.6, -5.05), Color = Color3.fromRGB(255, 220, 140), Material = Enum.Material.Neon })
end
-- Фары: невидимые источники света на носу корпуса
for _, x in { -1.6, 1.6 } do
local lamp = deco({ Size = Vector3.new(0.6, 0.5, 0.2), CFrame = CFrame.new(x, 2.98 - ride, FRONT_Z + 0.4), Transparency = 1 })
local light = Instance.new("SpotLight")
light.Face = Enum.NormalId.Front
light.Range = 55
@@ -285,8 +348,13 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
light.Parent = lamp
end
-- Пулемёт на капоте: основание приварено, турель крутится на Motor6D (C0 = наведение).
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.5, 1.3, 1.3), CFrame = GunMath.Mount * CFrame.new(0, -0.3, 0) * CFrame.Angles(0, 0, math.pi / 2), Color = DARK, Material = Enum.Material.Metal })
-- Пулемёт на стойке над кормой: основание приварено, турель крутится на Motor6D (C0 = наведение).
local mountBase = GunMath.Mount * CFrame.new(0, -0.3, 0)
local deckY = 3.6 - ride -- верх кормы корпуса над землёй ≈ 3.6
local postLength = mountBase.Y - deckY
deco({ Size = Vector3.new(0.45, postLength, 0.45), CFrame = CFrame.new(mountBase.X, deckY + postLength / 2, mountBase.Z), Color = DARK, Material = Enum.Material.Metal })
deco({ Size = Vector3.new(1.4, 0.2, 1.4), CFrame = CFrame.new(mountBase.X, deckY + 0.1, mountBase.Z), Color = DARK, Material = Enum.Material.DiamondPlate })
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.5, 1.3, 1.3), CFrame = mountBase * CFrame.Angles(0, 0, math.pi / 2), Color = DARK, Material = Enum.Material.Metal })
local turret = newPart(model, "Part", {
Name = "GunTurret",
Size = Vector3.new(0.6, 0.6, 0.6),
@@ -366,10 +434,9 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
flashLight.Enabled = false
flashLight.Parent = flash
-- Мотор сзади, выхлопные трубы, запаска
deco({ Size = Vector3.new(4, 1.8, 2.4), CFrame = CFrame.new(0, 1.4, 3.9), Color = DARK, Material = Enum.Material.Metal })
for _, x in { -1.4, 1.4 } do
local pipe = deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(2.6, 0.5, 0.5), CFrame = CFrame.new(x, 3.1, 4.7) * CFrame.Angles(0, 0, math.pi / 2), Color = STEEL, Material = Enum.Material.Metal })
-- Выхлоп: дымок из кормы (мотор и трубы — в самой модели)
for _, x in { -1.2, 1.2 } do
local pipe = deco({ Size = Vector3.new(0.3, 0.3, 0.3), CFrame = CFrame.new(x, 2.7 - ride, REAR_Z - 0.3), Transparency = 1 })
local smoke = Instance.new("Smoke")
smoke.Color = Color3.fromRGB(60, 55, 50)
smoke.Opacity = 0.15
@@ -377,12 +444,12 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
smoke.Size = 1
smoke.Parent = pipe
end
deco({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.9, 2.8, 2.8), CFrame = CFrame.new(0, 2.6, 5.5) * CFrame.Angles(0, math.pi / 2, 0), Color = TIRE, Material = Enum.Material.Fabric })
-- Колёса: рама → ступица (ход подвески) → [поворотный кулак] → колесо (мотор)
local motors, servos = {}, {}
for _, w in WHEELS do
local center = Vector3.new(w.x, WHEEL_Y, w.z)
local R = wheelRadius(w.axle)
local center = Vector3.new(w.x, R - ride, w.z) -- колесо касается земли
local hub = newPart(model, "Part", { Name = w.name .. "Hub", Size = Vector3.new(1, 1, 1), CFrame = cf * CFrame.new(center), CanCollide = false, Transparency = 1 })
local slide = Instance.new("PrismaticConstraint")
@@ -420,42 +487,22 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
axleParent = knuckle
end
-- У цилиндра ось вдоль X — совпадает с осью колеса.
-- Физическое колесо — невидимый цилиндр (ось вдоль X); на нём меш колеса из модели.
local wheelWidth = w.axle.size.Z * S * widthScale
local wheel = newPart(model, "Part", {
Name = w.name .. "Wheel",
Shape = Enum.PartType.Cylinder,
Size = Vector3.new(WIDTH, R * 2, R * 2),
Size = Vector3.new(wheelWidth, R * 2, R * 2),
CFrame = cf * CFrame.new(center),
Color = TIRE,
Material = Enum.Material.Fabric,
-- Под гусеницами колесо невидимое и цепляется сильнее.
Transparency = if wheelSpec.tracks then 1 else 0,
Transparency = 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",
Shape = Enum.PartType.Cylinder,
Size = Vector3.new(WIDTH + 0.1, R * 1.1, R * 1.1),
CFrame = wheel.CFrame,
Color = FRAME,
Material = FRAME_MAT,
Transparency = wheel.Transparency,
CanCollide = false,
Massless = true,
})
weld(wheel, rim)
-- Спица, чтобы было видно вращение
local spoke = newPart(model, "Part", {
Name = w.name .. "Spoke",
Size = Vector3.new(WIDTH + 0.15, R * 1.5, 0.3),
CFrame = wheel.CFrame,
Color = STEEL,
Material = Enum.Material.Metal,
Transparency = wheel.Transparency,
CanCollide = false,
Massless = true,
})
weld(wheel, spoke)
if not wheelSpec.tracks then
local scale = Vector3.new(S * wheelScale, S * wheelScale, S * widthScale)
local visual = meshPart(model, w.name .. "Visual", w.axle, wheel.CFrame * (if w.side < 0 then MESH_TURN_LEFT else MESH_TURN), scale)
weld(wheel, visual)
end
-- При повороте руля и ходе подвески колесо заходит под раму — не даём им цепляться.
for _, body in { chassis, seat } do
@@ -471,7 +518,8 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
motor.ActuatorType = Enum.ActuatorType.Motor
motor.MotorMaxTorque = B.CoastTorque * B.MassScale
motor.Parent = wheel
table.insert(motors, { motor = motor, x = w.x }) -- x — сторона колеса для дифференциала
-- x — сторона колеса для дифференциала, radius — у передних и задних колёс он разный
table.insert(motors, { motor = motor, x = w.x, radius = R })
end
-- Витрина: всё остаётся закреплённым, сесть нельзя.
@@ -558,7 +606,7 @@ function Buggy.Build(groundCFrame: CFrame, options): Model
chassis = chassis,
motors = motors,
servos = servos,
wheelRadius = R,
rideHeight = ride, -- центр рамы над землёй, когда машина стоит на колёсах
speedFactor = Buggy.SpeedFactor(setup),
ramSlow = BuggyStats.RamSlow(setup), -- доля скорости, теряемая при ударе о зомби
owner = owner,
@@ -606,7 +654,28 @@ function Buggy.FindDrivenBy(player: Player): Model?
return nil
end
-- Перевернуть на колёса и чуть приподнять.
-- Поставить машину на место ground (точка на земле, смотрит туда же): ровно, на колёса, без скорости.
-- Для построения команды после победы.
function Buggy.Place(model: Model, ground: CFrame)
local data = active[model]
if not data then
return
end
local position = ground.Position + Vector3.new(0, data.rideHeight + 0.5, 0)
model:PivotTo(CFrame.lookAt(position, position + ground.LookVector * Vector3.new(1, 0, 1)))
for _, d in model:GetDescendants() do
if d:IsA("BasePart") then
d.AssemblyLinearVelocity = Vector3.zero
d.AssemblyAngularVelocity = Vector3.zero
end
end
end
-- Вызывается перед переворотом: onFlip(model, position) — Zombies расталкивает зомби вокруг и прикрывает водителя.
Buggy.onFlip = nil :: ((Model, Vector3) -> ())?
-- Перевернуть на колёса: ставим ровно (без наклона) на землю под машиной, чуть выше — мягко опустится на подвеску.
-- Землю ищем с группой столкновений багги — зомби (сквозь них багги проходит) не мешают и под колёса не попадают.
function Buggy.Flip(model: Model)
local data = active[model]
if not data then
@@ -617,7 +686,20 @@ function Buggy.Flip(model: Model)
if look.Magnitude < 0.1 then
look = Vector3.new(0, 0, -1)
end
local position = chassis.Position + Vector3.new(0, 5, 0)
if Buggy.onFlip then
Buggy.onFlip(model, chassis.Position)
end
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude
params.FilterDescendantsInstances = { model }
params.CollisionGroup = Buggy.COLLISION_GROUP
params.RespectCanCollide = true
local hit = workspace:Raycast(chassis.Position + Vector3.new(0, 12, 0), Vector3.new(0, -60, 0), params)
local rideHeight = data.rideHeight -- центр рамы над землёй на колёсах (как в Buggy.Build)
local position = if hit
then Vector3.new(chassis.Position.X, hit.Position.Y + rideHeight + 0.8, chassis.Position.Z)
else chassis.Position + Vector3.new(0, 5, 0)
model:PivotTo(CFrame.lookAt(position, position + look.Unit))
for _, d in model:GetDescendants() do
if d:IsA("BasePart") then
@@ -699,8 +781,6 @@ function Buggy.Start()
end
local turnSign = if steer > 0 then 1 else -1 -- вправо — центр поворота справа (+X рамы)
-- Вперёд — это -Z рамы, поэтому колёса крутим в отрицательную сторону вокруг оси X.
local angular = -speed / data.wheelRadius * B.DriveSign
-- Тяга растёт вместе с массой — разгон как у лёгкой машины.
torque *= B.MassScale
for _, wheel in data.motors do
@@ -708,7 +788,9 @@ function Buggy.Start()
if turnRadius < math.huge then
factor = math.clamp((turnRadius - turnSign * wheel.x) / turnRadius, 0.55, 1.45)
end
wheel.motor.AngularVelocity = angular * factor
-- Вперёд — это -Z рамы, поэтому колёса крутим в отрицательную сторону вокруг оси X.
-- Скорость колеса — из его радиуса (задние у модели крупнее передних).
wheel.motor.AngularVelocity = -speed / wheel.radius * B.DriveSign * factor
wheel.motor.MotorMaxTorque = torque
end
+19 -12
View File
@@ -165,7 +165,7 @@ end
-- ===== Разбитые багги =====
local function stripWheel(model: Model, name: string)
for _, suffix in { "Wheel", "Rim", "Spoke" } do
for _, suffix in { "Wheel", "Visual" } do
local p = model:FindFirstChild(name .. suffix)
if p then
p:Destroy()
@@ -239,6 +239,9 @@ local function wreck(x: number, z: number, heading: number, variant: string)
else
d.Color = d.Color:Lerp(BURNT, burnt)
end
elseif d:IsA("SpecialMesh") then
-- Корпус и колёса модели — меши: затемняем текстуру
d.VertexColor *= 1 - burnt * 0.75
elseif d:IsA("Light") or d:IsA("Smoke") then
d:Destroy()
end
@@ -247,18 +250,22 @@ local function wreck(x: number, z: number, heading: number, variant: string)
local chassis = model.PrimaryPart
local c = chassis.CFrame
local height = c.Y - F -- центр рамы над полом
-- Габариты корпуса модели относительно центра рамы (Config.Buggy.Model, масштаб 0.86)
local BOTTOM = 1.69 -- низ корпуса под центром рамы
local ROOF = 5.43 -- верх высокой дуги над центром рамы
local REAR_AXLE, LENGTH, HALF_WIDTH = 5.63, 13.1, 7.4
if variant == "stands" or variant == "stripped" then
for _, name in { "FL", "FR", "RL", "RR" } do
stripWheel(model, name)
end
if variant == "stripped" then
model:PivotTo(c - Vector3.new(0, height - 0.5, 0))
model:PivotTo(c - Vector3.new(0, height - BOTTOM, 0))
else
for _, sx in { -2.3, 2.3 } do
for _, sz in { -3.6, 3.6 } do
local h = height - 0.5
local foot = c * CFrame.new(sx, -0.5 - h / 2, sz)
for _, sx in { -2.6, 2.6 } do
for _, sz in { -4.8, 4.8 } do
local h = height - 0.8
local foot = c * CFrame.new(sx, -0.8 - h / 2, sz)
part({ Size = Vector3.new(0.6, h, 0.6), CFrame = foot, Color = Color3.fromRGB(170, 40, 30), Material = Enum.Material.Metal })
part({ Size = Vector3.new(1.6, 0.3, 1.6), CFrame = CFrame.new(foot.X, F + 0.15, foot.Z), Color = DARK, Material = Enum.Material.Metal })
end
@@ -266,25 +273,25 @@ local function wreck(x: number, z: number, heading: number, variant: string)
end
elseif variant == "flipped" then
stripWheel(model, ({ "FL", "FR", "RL", "RR" })[rng:NextInteger(1, 4)])
model:PivotTo(CFrame.new(c.X, F + 4.85, c.Z) * c.Rotation * CFrame.Angles(0, 0, math.pi))
model:PivotTo(CFrame.new(c.X, F + ROOF, c.Z) * c.Rotation * CFrame.Angles(0, 0, math.pi))
elseif variant == "noseDown" then
stripWheel(model, "FL")
stripWheel(model, "FR")
-- Опрокидываем вперёд вокруг линии касания задних колёс.
local pivot = c * CFrame.new(0, -height, 3.6)
local angle = math.atan((height - 0.6) / 9.1)
-- Опрокидываем вперёд вокруг линии касания задних колёс, пока нос не ляжет на пол.
local pivot = c * CFrame.new(0, -height, REAR_AXLE)
local angle = math.atan((height - BOTTOM) / LENGTH)
model:PivotTo(pivot * CFrame.Angles(-angle, 0, 0) * pivot:Inverse() * c)
elseif variant == "tilted" then
stripWheel(model, "FL")
stripWheel(model, "RL")
-- Заваливаем на левый бок вокруг правых колёс.
local pivot = c * CFrame.new(3.9, -height, 0)
local angle = math.atan((height - 0.5) / 6.9)
local angle = math.atan((height - BOTTOM) / HALF_WIDTH)
model:PivotTo(pivot * CFrame.Angles(0, 0, angle) * pivot:Inverse() * c)
end
if variant == "burnt" or rng:NextNumber() < 0.2 then
local engine = part({ Size = Vector3.new(1, 1, 1), CFrame = chassis.CFrame * CFrame.new(0, 1.5, 3.9), Transparency = 1, CanCollide = false, Parent = model })
local engine = part({ Size = Vector3.new(1, 1, 1), CFrame = chassis.CFrame * CFrame.new(0, 0.6, 5.5), Transparency = 1, CanCollide = false, Parent = model })
burn(engine, 5)
end
if variant ~= "burnt" and rng:NextNumber() < 0.5 then
+61
View File
@@ -14,6 +14,7 @@ local Hangar = require(script.Parent.Hangar)
local Buggy = require(script.Parent.Buggy)
local Drops = require(script.Parent.Drops)
local MapEvents = require(script.Parent.MapEvents)
local Shards = require(script.Parent.Shards)
local World = require(script.Parent.World)
local Zombies = require(script.Parent.Zombies)
@@ -29,6 +30,7 @@ local DARK = Color3.fromRGB(38, 36, 34)
local circles = {}
local RoundRemote: RemoteEvent -- отсчёт перед раундом: клиенту приходит время старта (Round.client)
local IntroRemote: RemoteEvent -- пролёт камеры перед боем: багги команды и время начала (Intro.client)
local VictoryRemote: RemoteEvent -- победа: итоги боя, багги и время начала сцены (Victory.client)
local lastAction = {} -- [Player] = os.clock()
local function part(parent: Instance, props): BasePart
@@ -288,6 +290,61 @@ local function leaveArena(player: Player, toHangar: boolean)
end
end
-- Победа (Zombies.onVictory): бонус каждому, багги на тормоз и в линию, как на старте, итоги боя на экраны
-- (VictoryStart, Victory.client), через VictoryTime секунд — все в ангар.
local function victory(index: number, stats, bossKiller: number?)
local WV = Config.Waves
local team = {}
for _, player in Players:GetPlayers() do
if player:GetAttribute("Arena") == index then
table.insert(team, player)
end
end
if #team == 0 then
return
end
table.sort(team, function(a, b)
return a.UserId < b.UserId
end)
local buggies, results = {}, {}
for k, player in team do
task.spawn(Shards.Add, player.UserId, WV.VictoryShards)
local stat = stats[player.UserId] or { kills = 0, shards = 0 }
table.insert(results, {
userId = player.UserId,
name = player.DisplayName,
kills = stat.kills,
shards = stat.shards + WV.VictoryShards,
boss = player.UserId == bossKiller,
})
local buggy = Garage.BuggyOf(player)
if buggy then
Buggy.SetLocked(buggy, true)
Buggy.Place(buggy, World.ArenaSpawn(index, k, #team))
table.insert(buggies, buggy)
end
end
-- Места: больше убитых — выше, при равенстве — у кого больше осколков
table.sort(results, function(a, b)
if a.kills ~= b.kills then
return a.kills > b.kills
end
return a.shards > b.shards
end)
local startedAt = workspace:GetServerTimeNow()
for _, player in team do
VictoryRemote:FireClient(player, results, buggies, startedAt, WV.VictoryTime, WV.VictoryShards)
end
task.wait(WV.VictoryTime)
for _, player in team do
if player.Parent and player:GetAttribute("Arena") == index then
leaveArena(player, true)
end
end
end
local function validSize(value): boolean
return typeof(value) == "number" and value % 1 == 0 and value >= 1 and value <= L.MaxPlayers
end
@@ -399,6 +456,10 @@ function Lobby.Init(remotes: Folder)
IntroRemote = Instance.new("RemoteEvent")
IntroRemote.Name = "IntroStart"
IntroRemote.Parent = remotes
VictoryRemote = Instance.new("RemoteEvent")
VictoryRemote.Name = "VictoryStart"
VictoryRemote.Parent = remotes
Zombies.onVictory = victory
local ActionRemote = Instance.new("RemoteEvent")
ActionRemote.Name = "LobbyAction"
+6 -1
View File
@@ -228,7 +228,12 @@ local function tick()
local folder = Zombies.Battle(index)
local s = states[index]
if not folder then
states[index] = nil -- боя нет — объекты убрались вместе с папкой
-- Боя нет (команда ушла или победа) — убираем круги
if s then
remove(s.heal)
remove(s.boost)
states[index] = nil
end
continue
end
if not s or s.folder ~= folder then
+7
View File
@@ -5,6 +5,7 @@
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local Config = require(ReplicatedStorage.Shared.Config)
local Cases = require(script.Parent.Cases)
@@ -110,6 +111,12 @@ local function onPlayerAdded(player: Player)
s.canSave = ok
s.loaded = true
publish(userId)
-- Тесты в Studio: поднимаем баланс до StudioBalance, чтобы можно было всё купить и проверить.
local studio = Config.Shards.StudioBalance
if RunService:IsStudio() and studio and s.balance < studio then
Shards.Add(userId, studio - s.balance)
end
end
function Shards.Init()
+4 -5
View File
@@ -496,13 +496,12 @@ local function buildMap(map: Map, name: string)
map.ready = true
end
-- Куда поставить багги k-го из n игроков команды: по кругу в центре карты, мордой наружу.
-- Куда поставить багги k-го из n игроков команды: в линию плечом к плечу в центре карты, мордой вперёд (-Z).
-- Так команда стоит на старте и так же выстраивается после победы.
function World.ArenaSpawn(index: number, k: number, n: number): CFrame
local map = World.Arenas[index]
local angle = (k - 1) / n * math.pi * 2 + math.pi / 4 -- со сдвигом, чтобы не встать поперёк дорог
local out = Vector3.new(math.cos(angle), 0, math.sin(angle))
local at = map.origin + Vector3.new(0, W.BaseHeight, 0) + out * 16
return CFrame.lookAt(at, at + out)
local at = map.origin + Vector3.new((k - (n + 1) / 2) * 13, W.BaseHeight, 20)
return CFrame.lookAt(at, at + Vector3.new(0, 0, -1))
end
function World.ArenaReady(index: number): boolean
+188 -22
View File
@@ -13,6 +13,7 @@ local Debris = game:GetService("Debris")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local TweenService = game:GetService("TweenService")
local Config = require(ReplicatedStorage.Shared.Config)
local BuggyStats = require(ReplicatedStorage.Shared.BuggyStats)
@@ -39,6 +40,39 @@ local arenas = {}
local HitRemote: RemoteEvent
local ImpactRemote: RemoteEvent -- водителю: сбить скорость после удара о зомби
local WaveRemote: RemoteEvent -- игрокам карты: «волна N», «босс», «волна пройдена» (Round.client)
local shielded = {} -- [Player] = os.clock(), до которого зомби его не бьют (сразу после переворота багги)
local FLIP_CLEAR_RADIUS = 14 -- в каком радиусе от перевернувшейся багги зомби разлетаются
local FLIP_STUN = 1.5 -- сколько секунд они после этого стоят, а водитель защищён
-- Переворот багги (Buggy.Flip): зомби вокруг разлетаются в стороны и ненадолго оглушены,
-- водитель на это же время защищён — после переворота его не бьют сразу со всех сторон.
local function onFlip(model: Model, position: Vector3)
local now = os.clock()
for _, arena in arenas do
for _, data in arena.zombies do
if data.humanoid.Health <= 0 then
continue
end
local offset = (data.root.Position - position) * Vector3.new(1, 0, 1)
if offset.Magnitude < FLIP_CLEAR_RADIUS + data.reach then
local dir = if offset.Magnitude > 0.1 then offset.Unit else Vector3.new(rng:NextNumber(-1, 1), 0, rng:NextNumber(-1, 1)).Unit
data.root.AssemblyLinearVelocity = if data.boss then dir * 18 else dir * 45 + Vector3.new(0, 22, 0)
data.stunUntil = now + FLIP_STUN
-- Замах сорван: руки опускаются, удара не будет
data.windupUntil = nil
data.attackTarget = nil
for _, s in data.shoulders do
s.joint.C0 = s.base
end
end
end
end
local buggy = Buggy.Get(model)
if buggy and buggy.owner then
shielded[buggy.owner] = now + FLIP_STUN
end
end
-- ===== Модель =====
@@ -248,6 +282,16 @@ local function onDeath(arena, model: Model, data)
if killer and reward > 0 then
task.spawn(Shards.Add, killer.UserId, reward)
end
-- Статистика боя для итогов после победы
if killer then
local stat = arena.stats[killer.UserId] or { kills = 0, shards = 0 }
arena.stats[killer.UserId] = stat
stat.kills += 1
stat.shards += reward
if data.boss then
arena.bossKiller = killer.UserId
end
end
-- Бусты: из обычного зомби — иногда, из босса — несколько, разлетаются вокруг.
local position = data.root.Position
if data.boss then
@@ -266,7 +310,19 @@ local function onDeath(arena, model: Model, data)
end
Debris:AddItem(model, 3)
if data.boss then
if data.boss and arena.wave >= WV.Count then
-- Босс последней волны убит — ПОБЕДА: оставшихся зомби убираем, дальше церемония (Lobby)
arena.boss = nil
arena.phase = "victory"
for other in arena.zombies do
other:Destroy()
end
arena.zombies = {}
publish(arena)
if Zombies.onVictory then
task.spawn(Zombies.onVictory, arena.index, arena.stats, arena.bossKiller)
end
elseif data.boss then
-- Босс убит — передышка и следующая волна, больше прежней.
arena.boss = nil
arena.phase = "break"
@@ -284,29 +340,51 @@ end
-- Багги и зомби физически друг сквозь друга (группы столкновений в Buggy) — иначе зомби попадает под колесо,
-- как на трамплин, и машину переворачивает. Удар считаем сами: зомби внутри габаритов багги.
-- Габарит багги для зомби: корпус модели (≈ 15 в длину, 7 в ширину) плюс детали спереди.
local BOX_X, BOX_FRONT, BOX_BACK = 4.4, -10, 8
local function insideBuggy(chassis: BasePart, position: Vector3, reach: number): boolean
local p = chassis.CFrame:PointToObjectSpace(position)
return math.abs(p.X) < 4.8 + reach and p.Z > -8.5 - reach and p.Z < 6.5 + reach and p.Y > -4 and p.Y < 5 + reach * 2
return math.abs(p.X) < BOX_X + reach and p.Z > BOX_FRONT - reach and p.Z < BOX_BACK + reach and p.Y > -4 and p.Y < 6 + reach * 2
end
-- Зомби залез в габарит машины — сразу ставим его снаружи у ближайшего борта (в машину и на неё не забраться).
local function shoveOut(data, chassis: BasePart)
local p = chassis.CFrame:PointToObjectSpace(data.root.Position)
local margin = data.reach + 0.6
local toSide = BOX_X + margin - math.abs(p.X)
local toFront = p.Z - (BOX_FRONT - margin)
local toBack = BOX_BACK + margin - p.Z
local out
if toSide <= toFront and toSide <= toBack then
out = Vector3.new((if p.X >= 0 then 1 else -1) * (BOX_X + margin), 0, p.Z)
elseif toFront < toBack then
out = Vector3.new(p.X, 0, BOX_FRONT - margin)
else
out = Vector3.new(p.X, 0, BOX_BACK + margin)
end
local world = chassis.CFrame:PointToWorldSpace(out)
local position = Vector3.new(world.X, data.root.Position.Y, world.Z)
local look = data.root.CFrame.LookVector * Vector3.new(1, 0, 1)
data.root.CFrame = CFrame.lookAt(position, position + (if look.Magnitude > 0.1 then look else Vector3.zAxis))
data.root.AssemblyLinearVelocity = Vector3.zero
end
-- Багги на скорости сбивает зомби: урон от скорости, детали спереди и буст «Таран» добавляют, зомби отлетает,
-- машина теряет немного скорости (сколько — зависит от деталей и буста). Босса не отбросить, а машина
-- теряет втрое больше. Медленно наехал — обычного зомби просто отталкивает в сторону.
-- теряет втрое больше. Медленно наехал (или зомби сам зашёл) — его просто выталкивает наружу.
local function ram(data, buggyModel: Model, buggy)
local chassis = buggy.chassis
local speed = (chassis.AssemblyLinearVelocity - data.root.AssemblyLinearVelocity).Magnitude
if speed < Z.RamSpeed then
shoveOut(data, chassis)
return
end
local now = os.clock()
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
if not data.boss 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)
end
return
end
local driver = Buggy.Driver(buggyModel)
local ramBoost = BuggyStats.BoostMultiplier(driver, "ram")
if driver then
@@ -374,7 +452,17 @@ function spawnZombie(arena, targets, boss: boolean?)
lastRam = 0,
health = humanoid.Health,
walk = nil,
windupUntil = nil, -- идёт замах: удар в этот момент (os.clock)
attackTarget = nil,
shoulders = {}, -- { joint, base (C0 с вытянутыми руками), sign } — для анимации удара
}
local torso = model:FindFirstChild("Torso")
for name, sign in { ["Right Shoulder"] = 1, ["Left Shoulder"] = -1 } do
local joint = torso and torso:FindFirstChild(name) :: Motor6D?
if joint then
table.insert(data.shoulders, { joint = joint, base = joint.C0, sign = sign })
end
end
local animator = humanoid:FindFirstChildOfClass("Animator")
if animator then
local animation = Instance.new("Animation")
@@ -413,6 +501,61 @@ end
-- ===== ИИ =====
-- Куда бежать к игроку: если он за рулём — к борту машины напротив водителя (в машину зомби не заходит),
-- иначе прямо к нему.
local function goalFor(data, target): Vector3
local seat = target.humanoid.SeatPart
if not seat then
return target.root.Position
end
local chassis = seat.AssemblyRootPart
local p = chassis.CFrame:PointToObjectSpace(data.root.Position)
local seatZ = chassis.CFrame:PointToObjectSpace(seat.Position).Z
local side = if p.X >= 0 then 1 else -1
return chassis.CFrame:PointToWorldSpace(Vector3.new(side * (BOX_X + data.reach + 0.8), 0, seatZ))
end
-- Анимация удара руками: «raise» — замах над головой, «hit» — резкий удар вниз и возврат.
local function swing(data, phase: string)
for _, s in data.shoulders do
if phase == "raise" then
TweenService:Create(s.joint, TweenInfo.new(Z.AttackWindup, Enum.EasingStyle.Quad), { C0 = s.base * CFrame.Angles(0, 0, s.sign * 1.1) }):Play()
else
local down = TweenService:Create(s.joint, TweenInfo.new(0.12, Enum.EasingStyle.Quad, Enum.EasingDirection.In), { C0 = s.base * CFrame.Angles(0, 0, -s.sign * 0.5) })
down:Play()
down.Completed:Once(function()
if s.joint.Parent then
TweenService:Create(s.joint, TweenInfo.new(0.35), { C0 = s.base }):Play()
end
end)
end
end
end
-- Конец замаха: удар. Урон — только если цель всё ещё рядом (успел отъехать — промах).
local function strike(data)
local target = data.attackTarget
data.windupUntil = nil
data.attackTarget = nil
swing(data, "hit")
if not data.boss then
data.root.AssemblyLinearVelocity += data.root.CFrame.LookVector * 12 -- рывок вперёд
end
if not target or target.humanoid.Health <= 0 or not target.root.Parent then
return
end
if (target.root.Position - data.root.Position).Magnitude > data.attackRange + 1.5 then
return
end
if os.clock() < (shielded[target.player] or 0) then
return
end
-- Буст «Броня» из дропа и командная броня с карты уменьшают урон по игроку
local armor = Config.BoostById.armor
local reduce = math.min(0.8, armor.step * BuggyStats.BoostStacks(target.player, "armor") + BuggyStats.TeamBonus(target.player, "armor"))
target.humanoid:TakeDamage(data.attackDamage * (1 - reduce))
end
-- Зомби пропал не от рук игроков (провалился, отстал) — в волну он возвращается, босс появляется заново.
local function lose(arena, model: Model, data)
arena.zombies[model] = nil
@@ -451,28 +594,43 @@ local function think(arena)
if not data.boss then
alive += 1
end
if nearest and not arena.attacking then
-- Раунд ещё не начался: стоят.
if nearest and (not arena.attacking or now < (data.stunUntil or 0)) then
-- Раунд ещё не начался или зомби оглушён (разлетелся от переворота багги): стоит.
data.humanoid:MoveTo(data.root.Position)
if data.walk and data.walk.IsPlaying then
data.walk:Stop()
end
elseif nearest and data.windupUntil then
-- Замах: стоит и ждёт момента удара
data.humanoid:MoveTo(data.root.Position)
if now >= data.windupUntil then
strike(data)
end
elseif nearest then
-- Вне видимости бредут медленнее, заметив — бегут.
data.humanoid.WalkSpeed = data.speed * (if distance <= Z.SightRange then 1 else 0.6)
data.humanoid:MoveTo(nearest.root.Position)
data.humanoid:MoveTo(goalFor(data, nearest))
if data.walk then
if not data.walk.IsPlaying then
data.walk:Play()
end
data.walk:AdjustSpeed(data.humanoid.WalkSpeed / 14)
end
-- Подошёл — начинает замах: разворачивается к цели и поднимает руки. Урон будет только в момент удара.
if distance <= data.attackRange and now - data.lastAttack >= data.attackCooldown then
data.lastAttack = now
-- Буст «Броня» из дропа и командная броня с карты уменьшают урон по игроку
local armor = Config.BoostById.armor
local reduce = math.min(0.8, armor.step * BuggyStats.BoostStacks(nearest.player, "armor") + BuggyStats.TeamBonus(nearest.player, "armor"))
nearest.humanoid:TakeDamage(data.attackDamage * (1 - reduce))
data.windupUntil = now + Z.AttackWindup
data.attackTarget = nearest
data.humanoid:MoveTo(data.root.Position)
if data.walk then
data.walk:Stop()
end
local position = data.root.Position
local aim = Vector3.new(nearest.root.Position.X, position.Y, nearest.root.Position.Z)
if (aim - position).Magnitude > 0.1 then
data.root.CFrame = CFrame.lookAt(position, aim)
end
swing(data, "raise")
end
elseif data.walk and data.walk.IsPlaying then
data.walk:Stop()
@@ -515,7 +673,8 @@ function Zombies.Start(index: number)
local folder = Instance.new("Folder")
folder.Name = "Zombies" .. index
folder.Parent = workspace
local arena = { index = index, folder = folder, zombies = {}, attacking = false, pending = 0, wave = 1, phase = "wave", toSpawn = 0 }
-- stats — [userId] = { kills, shards } для итогов боя, bossKiller — кто добил последнего босса
local arena = { index = index, folder = folder, zombies = {}, attacking = false, pending = 0, wave = 1, phase = "wave", toSpawn = 0, stats = {}, bossKiller = nil }
arenas[index] = arena
startWave(arena, 1, false) -- первую волну объявляет «НАЧАЛИ!»
end
@@ -528,12 +687,15 @@ function Zombies.Attack(index: number)
end
end
-- Идёт ли бой на карте (после «НАЧАЛИ!»), и папка карты для её объектов.
-- Идёт ли бой на карте (после «НАЧАЛИ!», до победы), и папка карты для её объектов.
function Zombies.Battle(index: number): Folder?
local arena = arenas[index]
return if arena and arena.attacking then arena.folder else nil
return if arena and arena.attacking and arena.phase ~= "victory" then arena.folder else nil
end
-- Вызывается при победе: onVictory(номер карты, статистика { [userId] = { kills, shards } }, кто добил босса).
Zombies.onVictory = nil :: ((number, any, number?) -> ())?
function Zombies.Stop(index: number)
local arena = arenas[index]
if arena then
@@ -556,6 +718,10 @@ function Zombies.Init(remotes: Folder)
template = makeTemplate()
end)
RunService.Heartbeat:Connect(checkRams)
Buggy.onFlip = onFlip
Players.PlayerRemoving:Connect(function(player)
shielded[player] = nil
end)
task.spawn(function()
while true do
task.wait(THINK_INTERVAL)
+38 -1
View File
@@ -20,6 +20,38 @@ Config.Buggy = {
-- Если на W багги едет назад или руль перепутан — поменяйте знак на -1.
DriveSign = 1,
SteerSign = 1,
-- Внешний вид — модель из тулбокса, разрезанная на корпус и колёса (models/*.obj, импорт в Studio).
-- Корпус смотрит вперёд по −X меша, ось колёс — Z; размеры и смещения — в единицах меша, в игре × Scale.
-- Спереди у модели колёса крупнее (файл BuggyWheelRear — так он назван при разрезке), сзади — мельче.
-- forward — насколько ось колёс впереди центра корпуса (у задних — отрицательное), side — от середины до колеса,
-- radius — радиус колеса, Body.ground — высота центра корпуса над землёй.
Model = {
Scale = 0.86,
RideHeight = 2.6, -- центр рамы над землёй (со стандартными колёсами)
Tint = 0.55, -- насколько покраска из гаража окрашивает текстуру корпуса
Body = {
mesh = "rbxassetid://76247884850264",
texture = "rbxassetid://72437857687993",
size = Vector3.new(17.298, 8.277, 8.241),
ground = 5.199,
},
FrontWheel = {
mesh = "rbxassetid://109083080469614",
texture = "rbxassetid://87415891814423",
size = Vector3.new(4.1229, 4.1229, 1.3924),
radius = 2.061,
forward = 7.018,
side = 4.528,
},
RearWheel = {
mesh = "rbxassetid://128975430773192",
texture = "rbxassetid://84824182241205",
size = Vector3.new(3.8134, 3.8134, 1.1835),
radius = 1.907,
forward = -6.552,
side = 4.145,
},
},
-- Во сколько раз багги тяжелее «обычной»: тяга, пружины и демпферы умножаются на это же, поэтому
-- машина едет как раньше, но её не раскачивают взрывы и кочки.
MassScale = 4,
@@ -33,7 +65,7 @@ Config.Gun = {
CoolRate = 0.4, -- остывание в секунду
CoolResume = 0.3, -- после перегрева можно стрелять, когда остынет до этого уровня
YawLimit = 75, -- насколько турель поворачивается влево/вправо, градусы
PitchMin = -12,
PitchMin = -28, -- турель высоко на задней дуге — нужно доставать и до зомби вблизи
PitchMax = 30,
BarrelHealth = 3, -- попаданий до взрыва бочки
ExplosionRadius = 16,
@@ -161,6 +193,7 @@ Config.Zombies = {
AttackRange = 6.5,
AttackDamage = 8,
AttackCooldown = 1.1,
AttackWindup = 0.5, -- замах перед ударом: урон только в момент удара и только если цель ещё рядом
RamSpeed = 14, -- с какой скорости багги сбивает зомби
RamDamage = 2.2, -- урон тараном = (скорость − RamSpeed) × это, детали спереди добавляют сверху
-- Доля скорости, которую голая багги теряет при ударе о зомби. Каждая деталь с impact гасит часть:
@@ -187,6 +220,9 @@ Config.Waves = {
PerPlayer = 6, -- и ещё столько на каждого игрока команды
Growth = 8, -- каждая следующая волна больше на столько
Break = 8, -- секунд передышки после босса
Count = 1, -- после босса этой волны — ПОБЕДА: построение, итоги боя, возврат в ангар
VictoryShards = 50, -- бонус каждому игроку команды за победу
VictoryTime = 14, -- сколько секунд идёт сцена победы с итогами
}
Config.Boss = {
@@ -258,6 +294,7 @@ end
-- Выпадают на колесе фортуны и из кейсов (kind = "shards", amount = N).
Config.Shards = {
Start = 150, -- сколько у игрока с самого начала
StudioBalance = 150000, -- для тестов: при запуске в Studio баланс поднимается до этого (в опубликованной игре — нет)
Icon = "💎",
}
+1 -1
View File
@@ -5,7 +5,7 @@ local Config = require(script.Parent.Config)
local G = Config.Gun
local GunMath = {}
GunMath.Mount = CFrame.new(0, 1.9, -3.2) -- точка крепления турели относительно рамы
GunMath.Mount = CFrame.new(0, 6.2, 4.8) -- точка крепления турели относительно рамы: на высокой стойке над кормой, выше дуг кабины
GunMath.Muzzle = CFrame.new(0, 0.25, -4.6) -- срез ствола относительно турели
-- Углы турели (рад) в системе рамы для направления worldDir, с учётом ограничений.