commit a21365668918f75b909d3e40a64770804df3e1ff Author: Leshyi Date: Mon Nov 2 16:13:44 2026 +0300 1 diff --git a/Zombi/.gitignore b/Zombi/.gitignore new file mode 100644 index 0000000..628df60 --- /dev/null +++ b/Zombi/.gitignore @@ -0,0 +1,6 @@ +*.rbxl +*.rbxlx +*.rbxl.lock +*.rbxlx.lock +sourcemap.json +tools/ diff --git a/Zombi/default.project.json b/Zombi/default.project.json new file mode 100644 index 0000000..e92fe7b --- /dev/null +++ b/Zombi/default.project.json @@ -0,0 +1,28 @@ +{ + "name": "ApocalypseBuggy", + "tree": { + "$className": "DataModel", + "ReplicatedFirst": { + "Loading": { + "$path": "src/first/Loading.client.luau" + } + }, + "ReplicatedStorage": { + "Shared": { + "$path": "src/shared" + } + }, + "ServerScriptService": { + "Server": { + "$path": "src/server" + } + }, + "StarterPlayer": { + "StarterPlayerScripts": { + "Client": { + "$path": "src/client" + } + } + } + } +} diff --git a/Zombi/src/client/Cases.client.luau b/Zombi/src/client/Cases.client.luau new file mode 100644 index 0000000..edd3170 --- /dev/null +++ b/Zombi/src/client/Cases.client.luau @@ -0,0 +1,204 @@ +-- Меню кейсов: кнопка слева сверху со счётчиком, по ней — окно с кейсами и ключами. +-- Открыть кейс можно только ключом; ключа нет — сервер сразу предлагает купить его за Robux. + +local MarketplaceService = game:GetService("MarketplaceService") +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("Config")) +local Remotes = ReplicatedStorage:WaitForChild("Remotes") +local Action = Remotes:WaitForChild("CaseAction") +local Result = Remotes:WaitForChild("CaseResult") + +local CC = Config.Cases +local player = Players.LocalPlayer +local enabled = CC.ProductId ~= 0 and #CC.Loot > 0 + +local BG = Color3.fromRGB(30, 22, 16) +local CARD = Color3.fromRGB(52, 40, 30) +local ACCENT = Color3.fromRGB(150, 90, 40) +local ORANGE = Color3.fromRGB(230, 130, 40) +local PURPLE = Color3.fromRGB(150, 80, 210) +local TEXT = Color3.fromRGB(235, 220, 200) +local MUTED = Color3.fromRGB(170, 150, 130) + +-- ===== Интерфейс ===== + +local gui = Instance.new("ScreenGui") +gui.Name = "CasesHUD" +gui.ResetOnSpawn = false +gui.Parent = player:WaitForChild("PlayerGui") + +local function style(frame: GuiObject, radius: number, stroke: Color3) + Instance.new("UICorner", frame).CornerRadius = UDim.new(0, radius) + local s = Instance.new("UIStroke", frame) + s.ApplyStrokeMode = Enum.ApplyStrokeMode.Border + s.Color = stroke + s.Thickness = 2 +end + +local openButton = Instance.new("TextButton") +openButton.Position = UDim2.fromOffset(16, 60) +openButton.Size = UDim2.fromOffset(150, 40) +openButton.BackgroundColor3 = BG +openButton.BackgroundTransparency = 0.1 +openButton.Font = Enum.Font.GothamBlack +openButton.TextSize = 16 +openButton.TextColor3 = TEXT +openButton.Parent = gui +style(openButton, 10, PURPLE) + +-- Баланс осколков под кнопкой кейсов +local shardsLabel = Instance.new("TextLabel") +shardsLabel.Position = UDim2.fromOffset(16, 108) +shardsLabel.Size = UDim2.fromOffset(150, 34) +shardsLabel.BackgroundColor3 = BG +shardsLabel.BackgroundTransparency = 0.1 +shardsLabel.Font = Enum.Font.GothamBlack +shardsLabel.TextSize = 16 +shardsLabel.TextColor3 = Color3.fromRGB(120, 210, 230) +shardsLabel.Parent = gui +style(shardsLabel, 10, Color3.fromRGB(50, 140, 165)) +local function refreshShards() + shardsLabel.Text = ("%s %d осколков"):format(Config.Shards.Icon, player:GetAttribute("Shards") or 0) +end +player:GetAttributeChangedSignal("Shards"):Connect(refreshShards) +refreshShards() + +local panel = Instance.new("Frame") +panel.AnchorPoint = Vector2.new(0.5, 0.5) +panel.Position = UDim2.fromScale(0.5, 0.5) +panel.Size = UDim2.fromOffset(340, 0) +panel.AutomaticSize = Enum.AutomaticSize.Y +panel.BackgroundColor3 = BG +panel.BackgroundTransparency = 0.05 +panel.Visible = false +panel.Parent = gui +style(panel, 14, PURPLE) +local padding = Instance.new("UIPadding", panel) +padding.PaddingTop = UDim.new(0, 16) +padding.PaddingBottom = UDim.new(0, 16) +padding.PaddingLeft = UDim.new(0, 16) +padding.PaddingRight = UDim.new(0, 16) +local layout = Instance.new("UIListLayout", panel) +layout.SortOrder = Enum.SortOrder.LayoutOrder +layout.Padding = UDim.new(0, 10) + +local order = 0 +local function label(text: string, size: number, color: Color3, font: Enum.Font?): TextLabel + order += 1 + local l = Instance.new("TextLabel") + l.LayoutOrder = order + l.BackgroundTransparency = 1 + l.Size = UDim2.new(1, 0, 0, 0) + l.AutomaticSize = Enum.AutomaticSize.Y + l.Font = font or Enum.Font.GothamBold + l.TextSize = size + l.TextColor3 = color + l.TextWrapped = true + l.TextXAlignment = Enum.TextXAlignment.Left + l.Text = text + l.Parent = panel + return l +end + +local function button(text: string, color: Color3): TextButton + order += 1 + local b = Instance.new("TextButton") + b.LayoutOrder = order + b.Size = UDim2.new(1, 0, 0, 44) + b.BackgroundColor3 = color + b.Font = Enum.Font.GothamBlack + b.TextSize = 15 + b.TextColor3 = TEXT + b.Text = text + b.Parent = panel + Instance.new("UICorner", b).CornerRadius = UDim.new(0, 8) + return b +end + +label("КЕЙСЫ", 24, PURPLE, Enum.Font.GothamBlack) +local countLabel = label("", 16, TEXT) +label("Кейсы выпадают на колесе фортуны в ангаре. Открыть кейс можно только ключом — он покупается за Robux.", 13, MUTED, Enum.Font.GothamMedium) +local lootLabel = label("", 13, MUTED, Enum.Font.GothamMedium) +local actionButton = button("", ORANGE) +local resultLabel = label("", 15, ORANGE, Enum.Font.GothamBlack) +resultLabel.Visible = false +local closeButton = button("Закрыть", CARD) + +-- Что может выпасть +if #CC.Loot > 0 then + local names = {} + for _, item in CC.Loot do + table.insert(names, item.name) + end + lootLabel.Text = "Внутри: " .. table.concat(names, ", ") +else + lootLabel.Text = "Содержимое кейсов скоро появится — пока их можно только копить." +end + +local price: number? = nil -- цена ключа из Roblox, если товар задан +local refresh: () -> () + +local function loadPrice() + if CC.ProductId == 0 then + return + end + task.spawn(function() + local ok, info = pcall(function() + return MarketplaceService:GetProductInfo(CC.ProductId, Enum.InfoType.Product) + end) + if ok and info then + price = info.PriceInRobux + refresh() + end + end) +end + +function refresh() + local cases = player:GetAttribute("Cases") or 0 + local keys = player:GetAttribute("CaseKeys") or 0 + openButton.Text = ("🎁 КЕЙСЫ · %d"):format(cases) + countLabel.Text = ("Кейсов: %d · Ключей: %d"):format(cases, keys) + + local active = enabled and cases > 0 + if not enabled then + actionButton.Text = "Скоро" + elseif cases == 0 then + actionButton.Text = "Нет кейсов" + elseif keys > 0 then + actionButton.Text = "ОТКРЫТЬ КЕЙС" + else + actionButton.Text = if price then ("КУПИТЬ КЛЮЧ И ОТКРЫТЬ · R$ %d"):format(price) else "КУПИТЬ КЛЮЧ И ОТКРЫТЬ" + end + actionButton.AutoButtonColor = active + actionButton.BackgroundColor3 = if active then ORANGE else CARD + actionButton.TextColor3 = if active then BG else MUTED +end + +player:GetAttributeChangedSignal("Cases"):Connect(refresh) +player:GetAttributeChangedSignal("CaseKeys"):Connect(refresh) +refresh() +loadPrice() + +openButton.Activated:Connect(function() + panel.Visible = not panel.Visible + resultLabel.Visible = false + refresh() +end) +closeButton.Activated:Connect(function() + panel.Visible = false +end) +actionButton.Activated:Connect(function() + if enabled and (player:GetAttribute("Cases") or 0) > 0 then + resultLabel.Visible = false + Action:FireServer("open") + end +end) + +Result.OnClientEvent:Connect(function(name: string) + panel.Visible = true + resultLabel.Text = "Выпало: " .. name .. "!" + resultLabel.Visible = true + refresh() +end) diff --git a/Zombi/src/client/Driving.client.luau b/Zombi/src/client/Driving.client.luau new file mode 100644 index 0000000..849c782 --- /dev/null +++ b/Zombi/src/client/Driving.client.luau @@ -0,0 +1,123 @@ +-- Спидометр и подсказки за рулём, переворот багги на R и отсчёт автопереворота. +-- В бою (на карте команды) из багги не выйти: прыжок за рулём глушим, сервер всё равно посадит обратно. + +local ContextActionService = game:GetService("ContextActionService") +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") +local UserInputService = game:GetService("UserInputService") + +local Remotes = ReplicatedStorage:WaitForChild("Remotes") +local player = Players.LocalPlayer + +local gui = Instance.new("ScreenGui") +gui.Name = "BuggyHUD" +gui.ResetOnSpawn = false +gui.Parent = player:WaitForChild("PlayerGui") + +local hud = Instance.new("Frame") +hud.AnchorPoint = Vector2.new(0.5, 1) +hud.Position = UDim2.new(0.5, 0, 1, -24) +hud.Size = UDim2.fromOffset(260, 96) +hud.BackgroundColor3 = Color3.fromRGB(30, 22, 16) +hud.BackgroundTransparency = 0.25 +hud.Visible = false +hud.Parent = gui +Instance.new("UICorner", hud).CornerRadius = UDim.new(0, 12) +local stroke = Instance.new("UIStroke", hud) +stroke.Color = Color3.fromRGB(150, 90, 40) +stroke.Thickness = 2 + +local speedLabel = Instance.new("TextLabel") +speedLabel.BackgroundTransparency = 1 +speedLabel.Size = UDim2.new(1, 0, 0, 52) +speedLabel.Font = Enum.Font.GothamBlack +speedLabel.TextSize = 44 +speedLabel.TextColor3 = Color3.fromRGB(255, 190, 90) +speedLabel.Parent = hud + +local hint = Instance.new("TextLabel") +hint.BackgroundTransparency = 1 +hint.Position = UDim2.fromOffset(0, 54) +hint.Size = UDim2.new(1, 0, 0, 36) +hint.Font = Enum.Font.GothamMedium +hint.TextSize = 13 +hint.TextWrapped = true +hint.TextColor3 = Color3.fromRGB(220, 200, 180) +hint.Parent = hud + +-- Отсчёт автопереворота над спидометром +local flipLabel = Instance.new("TextLabel") +flipLabel.AnchorPoint = Vector2.new(0.5, 1) +flipLabel.Position = UDim2.new(0.5, 0, 0, -10) +flipLabel.Size = UDim2.fromOffset(320, 40) +flipLabel.BackgroundColor3 = Color3.fromRGB(30, 22, 16) +flipLabel.BackgroundTransparency = 0.15 +flipLabel.Font = Enum.Font.GothamBlack +flipLabel.TextSize = 22 +flipLabel.TextColor3 = Color3.fromRGB(255, 190, 90) +flipLabel.Visible = false +flipLabel.Parent = hud +Instance.new("UICorner", flipLabel).CornerRadius = UDim.new(0, 10) + +local function currentSeat(): VehicleSeat? + local character = player.Character + local humanoid = character and character:FindFirstChildOfClass("Humanoid") + local seat = humanoid and humanoid.SeatPart + if seat and seat:IsA("VehicleSeat") then + return seat + end + return nil +end + +local function inBattle(): boolean + return (player:GetAttribute("Arena") or 0) > 0 +end + +-- Прыжок за рулём в бою ничего не делает (на телефоне кнопку прыжка подстрахует сервер). +local jumpBlocked = false +local function setJumpBlocked(value: boolean) + if value == jumpBlocked then + return + end + jumpBlocked = value + if value then + ContextActionService:BindActionAtPriority("BlockSeatExit", function() + return Enum.ContextActionResult.Sink + end, false, Enum.ContextActionPriority.High.Value, Enum.KeyCode.Space, Enum.KeyCode.ButtonA) + else + ContextActionService:UnbindAction("BlockSeatExit") + end +end + +RunService.RenderStepped:Connect(function() + local seat = currentSeat() + local battle = inBattle() + hud.Visible = seat ~= nil + setJumpBlocked(seat ~= nil and battle) + if not seat then + return + end + -- 1 stud ≈ 0.28 м, поэтому studs/с почти равны км/ч. + local speed = seat.AssemblyLinearVelocity.Magnitude + speedLabel.Text = ("%d км/ч"):format(math.floor(speed + 0.5)) + hint.Text = if battle + then "WASD — езда · ЛКМ — огонь · R — перевернуть · в бою из багги не выйти" + else "WASD — езда · ЛКМ — огонь · R — перевернуть · Space — выйти" + + local model = seat:FindFirstAncestorOfClass("Model") + local flipAt = model and model:GetAttribute("FlipAt") + if flipAt then + local left = math.max(0, flipAt - workspace:GetServerTimeNow()) + flipLabel.Text = ("ПЕРЕВОРОТ ЧЕРЕЗ %d"):format(math.ceil(left)) + flipLabel.Visible = true + else + flipLabel.Visible = false + end +end) + +UserInputService.InputBegan:Connect(function(input, processed) + if not processed and input.KeyCode == Enum.KeyCode.R and currentSeat() then + Remotes.FlipBuggy:FireServer() + end +end) diff --git a/Zombi/src/client/EdgeFog.client.luau b/Zombi/src/client/EdgeFog.client.luau new file mode 100644 index 0000000..f0e42e6 --- /dev/null +++ b/Zombi/src/client/EdgeFog.client.luau @@ -0,0 +1,86 @@ +-- Туман у края карты: на карте лёгкая дымка, чем ближе камера к границе, тем гуще атмосфера, +-- у края и за ним не видно ничего. Издалека край и небо над картой закрывают туманные слои (World.buildEdge). +-- Камеру не пускаем за край карты и выше туманного потолка — сразу после того, как её поставил модуль камеры. +-- Карты квадратные (Config.World.Size), центры в ряд по X через Config.Lobby.MapSpacing, Z = 0. +-- Гаражи далеко за картами — там ничего не трогаем. + +local Lighting = game:GetService("Lighting") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") + +local Config = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("Config")) + +local HALF = Config.World.Size / 2 +local SPACING = Config.Lobby.MapSpacing +local CEILING = Config.World.FogCeiling +local FOG_RANGE = 260 -- за сколько studs до края туман начинает сгущаться +-- У самого края и за ним: почти предельная плотность, туман вплотную к камере — дальше нескольких десятков studs не видно. +local EDGE_DENSITY = 0.97 +local EDGE_HAZE = 10 +local EDGE_OFFSET = 0.9 +local CAMERA_MARGIN = 4 -- насколько камера может подойти к краю карты +local CAMERA_TOP = CEILING - 20 -- выше камера не поднимается, туман над ней + +local atmosphere: Atmosphere? = nil +local baseDensity, baseHaze, baseOffset = 0, 0, 0 + +-- Центр карты, на которой точка (или nil, если точка далеко от всех карт — например, в гараже). +local function mapCenter(position: Vector3): Vector3? + local cx = math.floor(position.X / SPACING + 0.5) * SPACING + if math.abs(position.Z) > HALF + 800 or math.abs(position.X - cx) > HALF + 800 then + return nil + end + return Vector3.new(cx, 0, 0) +end + +-- 0 — далеко от края (или не на карте), 1 — у самой границы и за ней. +local function edgeFactor(position: Vector3): number + local center = mapCenter(position) + if not center then + return 0 + end + local toEdge = HALF - math.max(math.abs(position.X - center.X), math.abs(position.Z - center.Z)) + return math.clamp(1 - toEdge / FOG_RANGE, 0, 1) +end + +-- После модуля камеры: возвращаем камеру внутрь карты и под туманный потолок, направление взгляда не меняем. +RunService:BindToRenderStep("KeepCameraInZone", Enum.RenderPriority.Camera.Value + 1, function() + local camera = workspace.CurrentCamera + if camera.CameraType == Enum.CameraType.Scriptable then + return -- меню гаража и заставки ставят камеру сами + end + local cf = camera.CFrame + local center = mapCenter(cf.Position) + if not center then + return + end + local limit = HALF - CAMERA_MARGIN + local p = cf.Position + local clamped = Vector3.new( + math.clamp(p.X, center.X - limit, center.X + limit), + math.min(p.Y, CAMERA_TOP), + math.clamp(p.Z, center.Z - limit, center.Z + limit) + ) + if clamped ~= p then + camera.CFrame = CFrame.new(clamped) * cf.Rotation + end +end) + +local factor = 0 +RunService.RenderStepped:Connect(function(dt) + if not atmosphere or not atmosphere.Parent then + atmosphere = Lighting:FindFirstChildOfClass("Atmosphere") + if not atmosphere then + return + end + -- Обычные значения ставит сервер (World.setupLighting) — от них и считаем. + baseDensity, baseHaze, baseOffset = atmosphere.Density, atmosphere.Haze, atmosphere.Offset + factor = 0 + end + local target = edgeFactor(workspace.CurrentCamera.CFrame.Position) + factor += (target - factor) * math.min(dt * 3, 1) -- плавно, без скачков при телепорте + 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 +end) diff --git a/Zombi/src/client/Fortune.client.luau b/Zombi/src/client/Fortune.client.luau new file mode 100644 index 0000000..515b8b2 --- /dev/null +++ b/Zombi/src/client/Fortune.client.luau @@ -0,0 +1,110 @@ +-- Колесо фортуны: крутим колесо у себя по атрибутам модели (сервер в конце ставит итоговый угол), +-- показываем в подсказке E время до следующей попытки и всплывающее сообщение с выигрышем. + +local Players = game:GetService("Players") +local ProximityPromptService = game:GetService("ProximityPromptService") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") + +local Config = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("Config")) +local Remotes = ReplicatedStorage:WaitForChild("Remotes") +local Result = Remotes:WaitForChild("FortuneResult") + +local FC = Config.Fortune +local player = Players.LocalPlayer +local model = workspace:WaitForChild("FortuneWheel") + +local BG = Color3.fromRGB(30, 22, 16) +local ACCENT = Color3.fromRGB(150, 90, 40) +local ORANGE = Color3.fromRGB(230, 130, 40) + +-- ===== Всплывающее сообщение ===== + +local gui = Instance.new("ScreenGui") +gui.Name = "FortuneHUD" +gui.ResetOnSpawn = false +gui.Parent = player:WaitForChild("PlayerGui") + +local toast = Instance.new("TextLabel") +toast.AnchorPoint = Vector2.new(0.5, 0) +toast.Position = UDim2.new(0.5, 0, 0, 70) +toast.Size = UDim2.fromOffset(0, 44) +toast.AutomaticSize = Enum.AutomaticSize.X +toast.BackgroundColor3 = BG +toast.BackgroundTransparency = 0.1 +toast.Font = Enum.Font.GothamBlack +toast.TextSize = 18 +toast.TextColor3 = ORANGE +toast.Visible = false +toast.Parent = gui +Instance.new("UICorner", toast).CornerRadius = UDim.new(0, 10) +local toastStroke = Instance.new("UIStroke", toast) +toastStroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border +toastStroke.Color = ACCENT +toastStroke.Thickness = 2 +local toastPadding = Instance.new("UIPadding", toast) +toastPadding.PaddingLeft = UDim.new(0, 18) +toastPadding.PaddingRight = UDim.new(0, 18) + +local toastId = 0 +local function showToast(text: string) + toastId += 1 + local id = toastId + toast.Text = text + toast.Visible = true + task.delay(5, function() + if toastId == id then + toast.Visible = false + end + end) +end + +Result.OnClientEvent:Connect(showToast) + +-- ===== Таймер до следующей попытки ===== + +local function timeLeft(): number + return (player:GetAttribute("NextSpin") or 0) - workspace:GetServerTimeNow() +end + +local function format(seconds: number): string + seconds = math.ceil(seconds) + return ("%02d:%02d:%02d"):format(seconds // 3600, seconds // 60 % 60, seconds % 60) +end + +ProximityPromptService.PromptTriggered:Connect(function(prompt) + if prompt.Name == "FortunePrompt" and timeLeft() > 0 then + showToast("Колесо можно крутить через " .. format(timeLeft())) + end +end) + +-- Подсказка E у каждого игрока своя: меняем текст только у себя. +task.spawn(function() + while true do + local prompt = model:FindFirstChild("FortunePrompt", true) :: ProximityPrompt? + if prompt then + local left = timeLeft() + prompt.ActionText = if left > 0 then "Ещё " .. format(left) else "Крутить колесо" + end + task.wait(1) + end +end) + +-- ===== Вращение ===== + +local wheel = model:WaitForChild("Wheel") :: Model +local base = model:GetAttribute("Base") :: CFrame + +RunService.RenderStepped:Connect(function() + local start = model:GetAttribute("SpinStart") + if not start or not base or not wheel.PrimaryPart then + return + end + local t = (workspace:GetServerTimeNow() - start) / FC.SpinTime + if t < 0 or t >= 1 then + return -- по окончании сервер сам ставит колесо в итоговый угол + end + local from, to = model:GetAttribute("SpinFrom"), model:GetAttribute("SpinTo") + local eased = 1 - (1 - t) ^ 3 -- быстро раскручивается и долго замедляется + wheel:PivotTo(base * CFrame.Angles(0, 0, from + (to - from) * eased)) +end) diff --git a/Zombi/src/client/Garage.client.luau b/Zombi/src/client/Garage.client.luau new file mode 100644 index 0000000..8a98595 --- /dev/null +++ b/Zombi/src/client/Garage.client.luau @@ -0,0 +1,978 @@ +-- Меню апгрейда в личном гараже: камера облетает багги на подъёмнике, справа — панель. +-- Вкладка «Детали»: слоты (перед, колёса, зад, броня) и инвентарь клетками — деталь перетаскивается +-- из инвентаря в свой слот, из слота — обратно (или просто клик). Вкладка «Покраска» — цвета кузова и каркаса. +-- Открывается само при входе в гараж и по E у верстака. + +local Players = game:GetService("Players") +local ProximityPromptService = game:GetService("ProximityPromptService") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") +local UserInputService = game:GetService("UserInputService") + +local Config = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("Config")) +local BuggyStats = require(ReplicatedStorage.Shared:WaitForChild("BuggyStats")) +local Remotes = ReplicatedStorage:WaitForChild("Remotes") +local SetupRemote = Remotes:WaitForChild("GarageSetup") +local ActionRemote = Remotes:WaitForChild("GarageAction") + +local G = Config.Garage +local player = Players.LocalPlayer + +local BG = Color3.fromRGB(30, 22, 16) +local CARD = Color3.fromRGB(52, 40, 30) +local ACCENT = Color3.fromRGB(150, 90, 40) +local ORANGE = Color3.fromRGB(230, 130, 40) +local TEXT = Color3.fromRGB(235, 220, 200) +local MUTED = Color3.fromRGB(170, 150, 130) +local WHITE = Color3.fromRGB(255, 255, 255) +-- Клетки инвентаря «как в майнкрафте»: тёмные ячейки со светлой рамкой +local CELL = Color3.fromRGB(58, 52, 48) +local CELL_EDGE = Color3.fromRGB(120, 110, 100) + +local PANEL_W, PANEL_H = 420, 660 +local SLOT_SIZE = 70 -- пять слотов в ряд по ширине панели +local SHARD = Config.Shards.Icon +local SHARD_COLOR = Color3.fromRGB(120, 210, 230) +local CELL_SIZE = 64 +local GRID_COLUMNS = 5 +local GRID_ROWS = 3 +local GRID_INSET = 3 -- отступ сетки инвентаря от краёв прокрутки (больше толщины рамки клетки) + +-- ===== Интерфейс ===== + +local gui = Instance.new("ScreenGui") +gui.Name = "GarageHUD" +gui.ResetOnSpawn = false +gui.Parent = player:WaitForChild("PlayerGui") + +local panel = Instance.new("Frame") +panel.AnchorPoint = Vector2.new(1, 0.5) +panel.Position = UDim2.new(1, -20, 0.5, 0) +panel.Size = UDim2.fromOffset(PANEL_W, PANEL_H) +panel.BackgroundColor3 = BG +panel.BackgroundTransparency = 0.1 +panel.Visible = false +panel.Parent = gui +Instance.new("UICorner", panel).CornerRadius = UDim.new(0, 14) +local panelStroke = Instance.new("UIStroke", panel) +panelStroke.Color = ACCENT +panelStroke.Thickness = 2 +local padding = Instance.new("UIPadding", panel) +padding.PaddingTop = UDim.new(0, 16) +padding.PaddingBottom = UDim.new(0, 16) +padding.PaddingLeft = UDim.new(0, 16) +padding.PaddingRight = UDim.new(0, 16) +local layout = Instance.new("UIListLayout", panel) +layout.SortOrder = Enum.SortOrder.LayoutOrder +layout.Padding = UDim.new(0, 8) + +-- Маленькие экраны: уменьшаем панель целиком. +local scale = Instance.new("UIScale", panel) +local function fitPanel() + local viewport = workspace.CurrentCamera.ViewportSize + scale.Scale = math.min(1, (viewport.Y - 40) / PANEL_H, (viewport.X * 0.6) / PANEL_W) +end +workspace.CurrentCamera:GetPropertyChangedSignal("ViewportSize"):Connect(fitPanel) +fitPanel() + +local function label(parent: Instance, order: number, text: string, size: number, color: Color3, font: Enum.Font?): TextLabel + local l = Instance.new("TextLabel") + l.LayoutOrder = order + l.BackgroundTransparency = 1 + l.Size = UDim2.new(1, 0, 0, size + 4) + l.Font = font or Enum.Font.GothamBold + l.TextSize = size + l.TextColor3 = color + l.TextXAlignment = Enum.TextXAlignment.Left + l.Text = text + l.Parent = parent + return l +end + +local function row(parent: Instance, order: number, height: number): Frame + local f = Instance.new("Frame") + f.LayoutOrder = order + f.BackgroundTransparency = 1 + f.Size = UDim2.new(1, 0, 0, height) + f.Parent = parent + local l = Instance.new("UIListLayout", f) + l.FillDirection = Enum.FillDirection.Horizontal + l.Padding = UDim.new(0, 6) + l.Wraps = true + return f +end + +local function button(parent: Instance, text: string, width: number, height: number, color: Color3): TextButton + local b = Instance.new("TextButton") + b.Size = UDim2.fromOffset(width, height) + b.BackgroundColor3 = color + b.AutoButtonColor = true + b.Font = Enum.Font.GothamBold + b.TextSize = 14 + b.TextColor3 = TEXT + b.Text = text + b.Parent = parent + Instance.new("UICorner", b).CornerRadius = UDim.new(0, 8) + local stroke = Instance.new("UIStroke", b) + stroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border + stroke.Color = WHITE + stroke.Thickness = 0 + return b +end + +-- Вкладка: страница с вертикальным списком внутри панели. +local function page(order: number, height: number): Frame + local f = Instance.new("Frame") + f.LayoutOrder = order + f.BackgroundTransparency = 1 + f.Size = UDim2.new(1, 0, 0, height) + f.Parent = panel + local l = Instance.new("UIListLayout", f) + l.SortOrder = Enum.SortOrder.LayoutOrder + l.Padding = UDim.new(0, 8) + return f +end + +local titleLabel = label(panel, 1, "ГАРАЖ", 26, ORANGE, Enum.Font.GothamBlack) +-- Баланс осколков справа от заголовка +local balanceLabel = Instance.new("TextLabel") +balanceLabel.BackgroundTransparency = 1 +balanceLabel.Size = UDim2.fromScale(1, 1) +balanceLabel.Font = Enum.Font.GothamBlack +balanceLabel.TextSize = 20 +balanceLabel.TextColor3 = SHARD_COLOR +balanceLabel.TextXAlignment = Enum.TextXAlignment.Right +balanceLabel.Parent = titleLabel + +local function balance(): number + return player:GetAttribute("Shards") or 0 +end +local tabs = row(panel, 2, 34) +-- Всё, кроме страницы: отступы, заголовок, вкладки, подсказка, кнопки и промежутки между ними. +local PAGE_H = PANEL_H - 32 - 30 - 34 - 16 - 48 - 8 * 4 +local partsPage = page(3, PAGE_H) +local paintPage = page(3, PAGE_H) +paintPage.Visible = false + +local partsTab = button(tabs, "ДЕТАЛИ", 191, 34, ACCENT) +local paintTab = button(tabs, "ПОКРАСКА", 191, 34, CARD) +local setOffer: (kind: string?, key: any, price: number?, buyButton: TextButton?) -> () -- ниже, у кнопки покупки +local function showTab(parts: boolean) + setOffer(nil) + partsPage.Visible = parts + paintPage.Visible = not parts + partsTab.BackgroundColor3 = if parts then ACCENT else CARD + paintTab.BackgroundColor3 = if parts then CARD else ACCENT +end +partsTab.Activated:Connect(function() + showTab(true) +end) +paintTab.Activated:Connect(function() + showTab(false) +end) + +-- ===== Детали: клетки ===== + +-- Цвет каждого типа детали (слота): рамка и лёгкий оттенок клетки — сразу видно, что куда ставить. +local SLOT_COLOR = {} +local SLOT_ORDER = {} +for i, slot in G.Slots do + SLOT_COLOR[slot.id] = slot.color + SLOT_ORDER[slot.id] = i +end + +-- color — цвет типа детали; без него — пустая серая клетка. +local function cellFrame(parent: Instance, size: number, color: Color3?): TextButton + local c = Instance.new("TextButton") + c.Size = UDim2.fromOffset(size, size) + c.BackgroundColor3 = if color then CELL:Lerp(color, 0.22) else CELL + c.AutoButtonColor = false + c.Text = "" + c.Parent = parent + Instance.new("UICorner", c).CornerRadius = UDim.new(0, 6) + local stroke = Instance.new("UIStroke", c) + stroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border + stroke.Color = color or CELL_EDGE + stroke.Thickness = 2 + return c +end + +-- Значок детали внутри клетки: эмодзи и подпись снизу. +local function drawItem(cell: GuiObject, item) + local icon = Instance.new("TextLabel") + icon.Name = "Icon" + icon.BackgroundTransparency = 1 + icon.Size = UDim2.fromScale(1, 0.68) + icon.Font = Enum.Font.GothamBold + icon.TextScaled = true + icon.Text = item.icon or "?" + icon.TextColor3 = WHITE + icon.Parent = cell + local pad = Instance.new("UIPadding", icon) + pad.PaddingTop = UDim.new(0.12, 0) + pad.PaddingLeft = UDim.new(0.18, 0) + pad.PaddingRight = UDim.new(0.18, 0) + local name = Instance.new("TextLabel") + name.Name = "Caption" + name.BackgroundTransparency = 1 + name.Position = UDim2.fromScale(0.04, 0.7) + name.Size = UDim2.fromScale(0.92, 0.26) + name.Font = Enum.Font.GothamBold + name.TextScaled = true + name.TextColor3 = TEXT + name.Text = item.name + name.Parent = cell +end + +label(partsPage, 1, "УСТАНОВЛЕНО", 14, TEXT) +local slotRow = row(partsPage, 2, SLOT_SIZE + 20) +slotRow:FindFirstChildOfClass("UIListLayout").Padding = UDim.new(0, 8) +label(partsPage, 3, "ИНВЕНТАРЬ · перетащи в слот или кликни · 🔒 — купить за осколки", 12, MUTED, Enum.Font.GothamMedium) + +local grid = Instance.new("ScrollingFrame") +grid.LayoutOrder = 4 +grid.BackgroundTransparency = 1 +grid.BorderSizePixel = 0 +grid.Size = UDim2.new(1, 0, 0, GRID_ROWS * (CELL_SIZE + 6) + GRID_INSET * 2) +grid.CanvasSize = UDim2.new() +grid.AutomaticCanvasSize = Enum.AutomaticSize.Y +grid.ScrollBarThickness = 4 +grid.ScrollingDirection = Enum.ScrollingDirection.Y +grid.Parent = partsPage +-- Рамка клетки рисуется снаружи, а прокрутка обрезает всё за своим краем — отступаем на толщину рамки. +local gridPadding = Instance.new("UIPadding", grid) +gridPadding.PaddingTop = UDim.new(0, GRID_INSET) +gridPadding.PaddingBottom = UDim.new(0, GRID_INSET) +gridPadding.PaddingLeft = UDim.new(0, GRID_INSET) +gridPadding.PaddingRight = UDim.new(0, GRID_INSET) +local gridLayout = Instance.new("UIGridLayout", grid) +gridLayout.CellSize = UDim2.fromOffset(CELL_SIZE, CELL_SIZE) +gridLayout.CellPadding = UDim2.fromOffset(6, 6) +gridLayout.SortOrder = Enum.SortOrder.LayoutOrder + +-- Строка описания и кнопка покупки справа (видна, когда выбрана закрытая деталь или покраска). +local function infoRow(parent: Instance, order: number): (TextLabel, TextButton) + local f = Instance.new("Frame") + f.LayoutOrder = order + f.BackgroundTransparency = 1 + f.Size = UDim2.new(1, 0, 0, 40) + f.Parent = parent + local l = Instance.new("TextLabel") + l.BackgroundTransparency = 1 + l.Size = UDim2.new(1, -150, 1, 0) + l.Font = Enum.Font.GothamMedium + l.TextSize = 13 + l.TextColor3 = MUTED + l.TextWrapped = true + l.TextXAlignment = Enum.TextXAlignment.Left + l.TextYAlignment = Enum.TextYAlignment.Top + l.Text = "" + l.Parent = f + local b = button(f, "", 142, 38, ORANGE) + b.Position = UDim2.new(1, -142, 0, 1) + b.Font = Enum.Font.GothamBlack + b.TextSize = 13 + b.Visible = false + return l, b +end + +local infoLabel, partsBuy = infoRow(partsPage, 5) + +-- Предложение купить: { kind = "part" | "paint", key, price, button } +local offer = nil +local buyButtons = { partsBuy } + +local function refreshOffer() + for _, b in buyButtons do + b.Visible = offer ~= nil and offer.button == b + if b.Visible then + local enough = balance() >= offer.price + b.Text = (if enough then "КУПИТЬ · " else "НУЖНО ") .. SHARD .. " " .. offer.price + b.BackgroundColor3 = if enough then ORANGE else CARD + b.TextColor3 = if enough then BG else MUTED + b.AutoButtonColor = enough + end + end +end + +function setOffer(kind: string?, key, price: number?, buyButton: TextButton?) + offer = if kind then { kind = kind, key = key, price = price, button = buyButton } else nil + refreshOffer() +end + +local function refreshBalance() + balanceLabel.Text = SHARD .. " " .. balance() + refreshOffer() +end +player:GetAttributeChangedSignal("Shards"):Connect(refreshBalance) +refreshBalance() + +local function onBuy() + if offer and balance() >= offer.price then + SetupRemote:FireServer("buy", offer.kind, offer.key) + end +end +partsBuy.Activated:Connect(onBuy) + +local function describe(item, force: boolean?) + if item and (force or not offer) then + infoLabel.Text = item.name .. " — " .. (item.info or "") + infoLabel.TextColor3 = MUTED:Lerp(SLOT_COLOR[item.slot] or MUTED, 0.5) + end +end + +-- Слоты: клетка + подпись под ней. slotCells[id] = { cell, slot } +local slotCells = {} +for _, slot in G.Slots do + local holder = Instance.new("Frame") + holder.BackgroundTransparency = 1 + holder.Size = UDim2.fromOffset(SLOT_SIZE, SLOT_SIZE + 20) + holder.Parent = slotRow + local cell = cellFrame(holder, SLOT_SIZE, slot.color) + local caption = Instance.new("TextLabel") + caption.BackgroundTransparency = 1 + caption.Position = UDim2.fromOffset(0, SLOT_SIZE + 2) + caption.Size = UDim2.fromOffset(SLOT_SIZE, 16) + caption.Font = Enum.Font.GothamBlack + caption.TextSize = 12 + caption.TextColor3 = slot.color + caption.Text = slot.name + caption.Parent = holder + slotCells[slot.id] = { cell = cell, slot = slot } +end + +-- ===== Перетаскивание ===== + +local drag = nil -- { item, fromSlot, start: Vector2, moved, ghost } +local cancelDrag: () -> () + +local function equipped(slotId: string): string + return player:GetAttribute("Buggy" .. string.upper(string.sub(slotId, 1, 1)) .. string.sub(slotId, 2)) or "" +end + +-- Во время перетаскивания слот для этой детали светится ярче и толще, остальные притухают. +local function highlight(slotId: string?) + for id, entry in slotCells do + local stroke = entry.cell:FindFirstChildOfClass("UIStroke") + local color = SLOT_COLOR[id] + if slotId == nil then + stroke.Color, stroke.Thickness, stroke.Transparency = color, 2, 0 + entry.cell.BackgroundColor3 = CELL:Lerp(color, 0.22) + elseif slotId == id then + stroke.Color, stroke.Thickness, stroke.Transparency = color:Lerp(WHITE, 0.35), 4, 0 + entry.cell.BackgroundColor3 = CELL:Lerp(color, 0.45) + else + stroke.Color, stroke.Thickness, stroke.Transparency = color, 2, 0.7 + entry.cell.BackgroundColor3 = CELL + end + end +end + +local function slotAt(position: Vector2): string? + for id, entry in slotCells do + local p, s = entry.cell.AbsolutePosition, entry.cell.AbsoluteSize + if position.X >= p.X and position.X <= p.X + s.X and position.Y >= p.Y and position.Y <= p.Y + s.Y then + return id + end + end + return nil +end + +local function beginDrag(item, fromSlot: string?, input: InputObject) + if drag then + return + end + describe(item) + drag = { item = item, fromSlot = fromSlot, start = Vector2.new(input.Position.X, input.Position.Y), moved = false } +end + +local function moveDrag(position: Vector2) + if not drag then + return + end + if not drag.moved and (position - drag.start).Magnitude > 6 then + drag.moved = true + local ghost = cellFrame(gui, CELL_SIZE, SLOT_COLOR[drag.item.slot]) + ghost.AnchorPoint = Vector2.new(0.5, 0.5) + ghost.BackgroundTransparency = 0.15 + ghost.Active = false + ghost.ZIndex = 10 + drawItem(ghost, drag.item) + for _, d in ghost:GetDescendants() do + if d:IsA("GuiObject") then + d.ZIndex = 11 + end + end + drag.ghost = ghost + highlight(drag.item.slot) -- подсвечиваем, куда эту деталь можно поставить + end + if drag.ghost then + drag.ghost.Position = UDim2.fromOffset(position.X, position.Y) + end +end + +local function endDrag(position: Vector2) + if not drag then + return + end + local d = drag + drag = nil + if d.ghost then + d.ghost:Destroy() + end + highlight(nil) + if not d.moved then + -- Просто клик: из инвентаря — поставить, из слота — снять. + if d.fromSlot then + SetupRemote:FireServer("unequip", d.fromSlot) + else + SetupRemote:FireServer("equip", d.item.id) + end + return + end + local target = slotAt(position) + if target == d.item.slot then + if not d.fromSlot then + SetupRemote:FireServer("equip", d.item.id) + end + elseif d.fromSlot then + SetupRemote:FireServer("unequip", d.fromSlot) -- вытащили из слота мимо — деталь возвращается в инвентарь + end +end + +-- Меню закрылось посреди перетаскивания — ничего не меняем. +function cancelDrag() + if drag and drag.ghost then + drag.ghost:Destroy() + end + drag = nil + highlight(nil) +end + +local function isPointer(input: InputObject): boolean + return input.UserInputType == Enum.UserInputType.MouseButton1 or input.UserInputType == Enum.UserInputType.Touch +end + +UserInputService.InputChanged:Connect(function(input) + if input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch then + moveDrag(Vector2.new(input.Position.X, input.Position.Y)) + end +end) +UserInputService.InputEnded:Connect(function(input) + if isPointer(input) then + endDrag(Vector2.new(input.Position.X, input.Position.Y)) + end +end) + +-- ===== Характеристики ===== +-- Карточка слева внизу: текущие характеристики багги. При наведении на деталь (или пока её тащишь) +-- показывает, какими они станут: значение после замены и разница зелёным/красным. + +local statsCard = Instance.new("Frame") +statsCard.AnchorPoint = Vector2.new(0, 1) +statsCard.Position = UDim2.new(0, 16, 1, -16) +statsCard.Size = UDim2.fromOffset(330, 0) +statsCard.AutomaticSize = Enum.AutomaticSize.Y +statsCard.BackgroundColor3 = BG +statsCard.BackgroundTransparency = 0.1 +statsCard.Visible = false +statsCard.Parent = gui +Instance.new("UICorner", statsCard).CornerRadius = UDim.new(0, 12) +local statsStroke = Instance.new("UIStroke", statsCard) +statsStroke.Color = ACCENT +statsStroke.Thickness = 2 +local statsPadding = Instance.new("UIPadding", statsCard) +statsPadding.PaddingTop = UDim.new(0, 12) +statsPadding.PaddingBottom = UDim.new(0, 12) +statsPadding.PaddingLeft = UDim.new(0, 14) +statsPadding.PaddingRight = UDim.new(0, 14) +local statsLayout = Instance.new("UIListLayout", statsCard) +statsLayout.SortOrder = Enum.SortOrder.LayoutOrder +statsLayout.Padding = UDim.new(0, 7) +local statsScale = Instance.new("UIScale", statsCard) +statsScale.Scale = scale.Scale +scale:GetPropertyChangedSignal("Scale"):Connect(function() + statsScale.Scale = scale.Scale +end) + +local statsTitle = label(statsCard, 0, "ХАРАКТЕРИСТИКИ", 14, ORANGE, Enum.Font.GothamBlack) + +-- Строки: скорость (км/ч, полоса — доля от максимума) и характеристики 0–100 из Config. +local STAT_ROWS = { { id = "speed", name = "Скорость", color = ORANGE, max = Config.Buggy.MaxSpeed, unit = " км/ч" } } +for _, stat in G.Stats do + table.insert(STAT_ROWS, { id = stat.id, name = stat.name, color = stat.color, max = 100, unit = "" }) +end + +local statRows = {} +for i, spec in STAT_ROWS do + local rowFrame = Instance.new("Frame") + rowFrame.LayoutOrder = i + rowFrame.BackgroundTransparency = 1 + rowFrame.Size = UDim2.new(1, 0, 0, 18) + rowFrame.Parent = statsCard + local name = Instance.new("TextLabel") + name.BackgroundTransparency = 1 + name.Size = UDim2.fromOffset(112, 18) + name.Font = Enum.Font.GothamBold + name.TextSize = 13 + name.TextColor3 = TEXT + name.TextXAlignment = Enum.TextXAlignment.Left + name.Text = spec.name + name.Parent = rowFrame + local track = Instance.new("Frame") + track.AnchorPoint = Vector2.new(0, 0.5) + track.Position = UDim2.new(0, 116, 0.5, 0) + track.Size = UDim2.fromOffset(100, 8) + track.BackgroundColor3 = CELL + track.BorderSizePixel = 0 + track.Parent = rowFrame + Instance.new("UICorner", track).CornerRadius = UDim.new(1, 0) + local fill = Instance.new("Frame") + fill.Size = UDim2.fromScale(0, 1) + fill.BackgroundColor3 = spec.color + fill.BorderSizePixel = 0 + fill.Parent = track + Instance.new("UICorner", fill).CornerRadius = UDim.new(1, 0) + local value = Instance.new("TextLabel") + value.BackgroundTransparency = 1 + value.Position = UDim2.fromOffset(222, 0) + value.Size = UDim2.fromOffset(52, 18) + value.Font = Enum.Font.GothamBlack + value.TextSize = 13 + value.TextColor3 = TEXT + value.TextXAlignment = Enum.TextXAlignment.Right + value.Parent = rowFrame + local delta = Instance.new("TextLabel") + delta.BackgroundTransparency = 1 + delta.Position = UDim2.fromOffset(276, 0) + delta.Size = UDim2.fromOffset(26, 18) + delta.Font = Enum.Font.GothamBlack + delta.TextSize = 12 + delta.TextXAlignment = Enum.TextXAlignment.Left + delta.Parent = rowFrame + statRows[spec.id] = { spec = spec, fill = fill, value = value, delta = delta } +end + +local function currentSetup() + local setup = {} + for _, slot in G.Slots do + setup[slot.id] = equipped(slot.id) + end + return setup +end + +-- Предпросмотр: { slot, id } — что будет стоять в слоте ("" — слот освободится); nil — без предпросмотра. +local preview = nil + +local function refreshStats() + local setup = currentSetup() + local now = BuggyStats.Compute(setup) + local after = now + if preview and setup[preview.slot] ~= preview.id then + setup[preview.slot] = preview.id + after = BuggyStats.Compute(setup) + statsTitle.Text = "ХАРАКТЕРИСТИКИ · если поставить" + else + statsTitle.Text = "ХАРАКТЕРИСТИКИ" + end + for id, row in statRows do + local value = after[id] + local diff = math.floor(value + 0.5) - math.floor(now[id] + 0.5) + row.fill.Size = UDim2.fromScale(math.clamp(value / row.spec.max, 0, 1), 1) + row.value.Text = math.floor(value + 0.5) .. row.spec.unit + row.delta.Text = if diff > 0 then "+" .. diff elseif diff < 0 then tostring(diff) else "" + row.delta.TextColor3 = if diff > 0 then Color3.fromRGB(110, 220, 100) else Color3.fromRGB(240, 90, 70) + end +end + +local function setPreview(item, removeFrom: string?) + if removeFrom then + preview = { slot = removeFrom, id = "" } + elseif item then + preview = { slot = item.slot, id = item.id } + else + preview = nil + end + refreshStats() +end + +-- Отпустили деталь — предпросмотр больше не нужен (новые значения придут вместе с установкой). +UserInputService.InputEnded:Connect(function(input) + if isPointer(input) and preview then + setPreview(nil) + end +end) + +-- locked — деталь ещё не куплена: клик предлагает купить, перетащить нельзя. +local function hook(cell: TextButton, item, fromSlot: string?, locked: boolean?) + cell.InputBegan:Connect(function(input) + if not isPointer(input) then + return + end + if locked then + setOffer("part", item.id, item.price, partsBuy) + describe(item, true) + else + setOffer(nil) + beginDrag(item, fromSlot, input) + end + setPreview(item, fromSlot) + end) + cell.MouseEnter:Connect(function() + describe(item) + if not drag then + setPreview(item, fromSlot) + end + end) + cell.MouseLeave:Connect(function() + if not drag then + setPreview(nil) + end + end) +end + +-- Закрытая деталь: клетка притушена, вместо подписи — цена, в углу замок. +local function markLocked(cell: GuiObject, item) + cell.BackgroundColor3 = CELL + local icon = cell:FindFirstChild("Icon") :: TextLabel + icon.TextTransparency = 0.55 + local caption = cell:FindFirstChild("Caption") :: TextLabel + caption.Text = SHARD .. " " .. (item.price or "?") + caption.TextColor3 = SHARD_COLOR + local lock = Instance.new("TextLabel") + lock.BackgroundTransparency = 1 + lock.Position = UDim2.new(1, -20, 0, 2) + lock.Size = UDim2.fromOffset(18, 18) + lock.Font = Enum.Font.GothamBold + lock.TextScaled = true + lock.Text = "🔒" + lock.Parent = cell +end + +-- Перерисовать слоты и инвентарь по атрибутам игрока. +local function refreshParts() + local owned = player:GetAttribute("OwnedParts") or "," + local inSlots = {} + for id, entry in slotCells do + local cell = entry.cell + for _, child in cell:GetChildren() do + if child:IsA("TextLabel") then + child:Destroy() + end + end + local item = Config.PartById[equipped(id)] + if item then + inSlots[item.id] = true + drawItem(cell, item) + else + local empty = Instance.new("TextLabel") + empty.BackgroundTransparency = 1 + empty.Size = UDim2.fromScale(1, 1) + empty.Font = Enum.Font.GothamBlack + empty.TextSize = 30 + empty.TextColor3 = SLOT_COLOR[id] + empty.TextTransparency = 0.4 + empty.Text = "+" + empty.Parent = cell + end + entry.item = item + end + + for _, child in grid:GetChildren() do + if child:IsA("GuiObject") then + child:Destroy() + end + end + -- Инвентарь по порядку типов (как слоты), внутри типа — как в Config. Закрытые детали тоже здесь, с ценой. + local items = {} + for index, item in G.Parts do + local has = string.find(owned, "," .. item.id .. ",", 1, true) ~= nil + if not inSlots[item.id] and (has or item.price) then + table.insert(items, { item = item, index = index, locked = not has }) + end + end + if offer and offer.kind == "part" and string.find(owned, "," .. offer.key .. ",", 1, true) then + setOffer(nil) -- только что купили + end + table.sort(items, function(a, b) + local sa, sb = SLOT_ORDER[a.item.slot] or 99, SLOT_ORDER[b.item.slot] or 99 + if sa ~= sb then + return sa < sb + end + return a.index < b.index + end) + local count = #items + for i, entry in items do + local cell = cellFrame(grid, CELL_SIZE, SLOT_COLOR[entry.item.slot]) + cell.LayoutOrder = i + drawItem(cell, entry.item) + if entry.locked then + markLocked(cell, entry.item) + end + hook(cell, entry.item, nil, entry.locked) + end + refreshStats() + -- Пустые клетки до полной сетки + for i = count + 1, math.max(GRID_COLUMNS * GRID_ROWS, count) do + local cell = cellFrame(grid, CELL_SIZE) + cell.LayoutOrder = i + cell.Active = false + end +end + +for id, entry in slotCells do + entry.cell.InputBegan:Connect(function(input) + if isPointer(input) and entry.item and not entry.slot.required then + beginDrag(entry.item, id, input) + end + end) + entry.cell.MouseEnter:Connect(function() + describe(entry.item) + -- Наведение на установленную деталь показывает, что будет, если её снять. + if entry.item and not entry.slot.required and not drag then + setPreview(nil, id) + end + end) + entry.cell.MouseLeave:Connect(function() + if not drag then + setPreview(nil) + end + end) +end + +player:GetAttributeChangedSignal("OwnedParts"):Connect(refreshParts) +for _, slot in G.Slots do + player:GetAttributeChangedSignal("Buggy" .. string.upper(string.sub(slot.id, 1, 1)) .. string.sub(slot.id, 2)):Connect(refreshParts) +end +refreshParts() +infoLabel.Text = "Наведи на деталь, чтобы узнать, что она даёт." + +-- ===== Покраска ===== + +-- Секции: key — поле настройки на сервере, attribute — откуда читаем текущий выбор. +local sections = {} +local paintOrder = 0 +local paintInfo: TextLabel, paintBuy: TextButton + +local function section(key: string, attribute: string, title: string, list) + paintOrder += 1 + local header = label(paintPage, paintOrder, title, 14, TEXT) + paintOrder += 1 + local container = row(paintPage, paintOrder, 0) + local buttons = {} + for index, item in list do + local b = button(container, "", 34, 34, item.color) + b.AutoButtonColor = false + if item.rare then + -- Замок, пока покраска не выиграна на колесе фортуны (см. refreshPaint) + local lock = Instance.new("TextLabel") + lock.Name = "Lock" + lock.Size = UDim2.fromScale(1, 1) + lock.BackgroundColor3 = BG + lock.BackgroundTransparency = 0.35 + lock.Font = Enum.Font.GothamBlack + lock.TextSize = 16 + lock.TextColor3 = TEXT + lock.Text = "🔒" + lock.Parent = b + Instance.new("UICorner", lock).CornerRadius = UDim.new(0, 8) + end + b.Activated:Connect(function() + local lock = b:FindFirstChild("Lock") + if lock and lock.Visible then + -- Закрытая покраска — предлагаем купить за осколки + setOffer("paint", index, item.price, paintBuy) + paintInfo.Text = item.name .. " — редкая покраска. Выпадает на колесе фортуны или покупается за осколки." + return + end + setOffer(nil) + SetupRemote:FireServer(key, index) + end) + table.insert(buttons, b) + end + -- Высоту ряда считаем по кнопкам (с переносом строк) + local listLayout = container:FindFirstChildOfClass("UIListLayout") + local function resize() + container.Size = UDim2.new(1, 0, 0, listLayout.AbsoluteContentSize.Y) + end + listLayout:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(resize) + resize() + local names = {} + for i, item in list do + names[i] = item.name + end + sections[key] = { attribute = attribute, header = header, title = title, names = names, buttons = buttons } +end + +section("paint", "BuggyPaint", "КУЗОВ", G.Paints) +section("accent", "BuggyAccent", "КАРКАС И ДИСКИ", G.Accents) +paintOrder += 1 +label(paintPage, paintOrder, "🔒 — редкие покраски: колесо фортуны или осколки", 12, MUTED, Enum.Font.GothamMedium) +paintOrder += 1 +paintInfo, paintBuy = infoRow(paintPage, paintOrder) +paintInfo.Text = "Кликни по покраске с замком, чтобы купить её." +table.insert(buyButtons, paintBuy) +paintBuy.Activated:Connect(onBuy) + +local function refreshPaint() + local owned = player:GetAttribute("RarePaints") or "," + if offer and offer.kind == "paint" and string.find(owned, "," .. offer.key .. ",", 1, true) then + setOffer(nil) -- только что купили + paintInfo.Text = "Покраска открыта — выбери её." + end + for _, s in sections do + local selected = player:GetAttribute(s.attribute) or 1 + s.header.Text = s.title .. " · " .. (s.names[selected] or "") + for index, b in s.buttons do + local lock = b:FindFirstChild("Lock") + if lock then + lock.Visible = not string.find(owned, "," .. index .. ",", 1, true) + end + b:FindFirstChildOfClass("UIStroke").Thickness = if index == selected then 3 else 0 + end + end +end +for _, s in sections do + player:GetAttributeChangedSignal(s.attribute):Connect(refreshPaint) +end +player:GetAttributeChangedSignal("RarePaints"):Connect(refreshPaint) +refreshPaint() + +-- ===== Кнопки действий ===== + +-- Выезда на карту из гаража нет: на карту попадают только через лобби в ангаре. +label(panel, 4, "На карту — через круги лобби в ангаре", 12, MUTED, Enum.Font.GothamMedium) +local actionRow = row(panel, 5, 48) +local lookButton = button(actionRow, "Осмотреться", (PANEL_W - 32 - 6) / 2, 48, CARD) +local leaveButton = button(actionRow, "В АНГАР", (PANEL_W - 32 - 6) / 2, 48, ORANGE) +leaveButton.Font = Enum.Font.GothamBlack +leaveButton.TextSize = 16 +leaveButton.TextColor3 = BG + +-- ===== Камера и открытие меню ===== + +local camera = workspace.CurrentCamera +local open = false +local orbit, dragging = 0, false +local savedWalk, savedJumpPower, savedJumpHeight + +local function humanoid(): Humanoid? + local character = player.Character + return character and character:FindFirstChildOfClass("Humanoid") +end + +local function myRoom(): Model? + local garages = workspace:FindFirstChild("Garages") + return garages and garages:FindFirstChild(tostring(player.UserId)) :: Model? +end + +local function displayModel(): Model? + local room = myRoom() + return room and room:FindFirstChild("Display") :: Model? +end + +-- Камера не выходит из комнаты: держим её внутри коробки стен с запасом. +local WALL_MARGIN = 2.5 +local function insideRoom(position: Vector3): Vector3 + local room = myRoom() + if not room then + return position + end + local box, size = room:GetBoundingBox() -- коробка по стенам, полу и потолку + local p = box:PointToObjectSpace(position) + local half = size / 2 - Vector3.new(WALL_MARGIN, WALL_MARGIN, WALL_MARGIN) + p = Vector3.new(math.clamp(p.X, -half.X, half.X), math.clamp(p.Y, -half.Y, half.Y), math.clamp(p.Z, -half.Z, half.Z)) + return box:PointToWorldSpace(p) +end + +local function setOpen(value: boolean) + if open == value then + return + end + open = value + panel.Visible = value + statsCard.Visible = value + dragging = false + local h = humanoid() + if value then + orbit = 0 + -- Пока открыто меню, персонаж стоит на месте. + if h then + savedWalk, savedJumpPower, savedJumpHeight = h.WalkSpeed, h.JumpPower, h.JumpHeight + h.WalkSpeed, h.JumpPower, h.JumpHeight = 0, 0, 0 + end + else + cancelDrag() + if h and savedWalk then + h.WalkSpeed, h.JumpPower, h.JumpHeight = savedWalk, savedJumpPower, savedJumpHeight + end + savedWalk = nil + camera.CameraType = Enum.CameraType.Custom + if h then + camera.CameraSubject = h + end + end +end + +leaveButton.Activated:Connect(function() + setOpen(false) + ActionRemote:FireServer("leave") +end) +lookButton.Activated:Connect(function() + setOpen(false) +end) + +player:GetAttributeChangedSignal("InGarage"):Connect(function() + setOpen(player:GetAttribute("InGarage") == true) +end) +player.CharacterAdded:Connect(function() + savedWalk = nil -- у нового персонажа скорость и так обычная + open = true + setOpen(false) +end) + +ProximityPromptService.PromptTriggered:Connect(function(prompt) + if prompt.Name == "TuningPrompt" and player:GetAttribute("InGarage") then + setOpen(true) + end +end) + +-- Крутим камеру мышью (или пальцем) по свободной части экрана. +UserInputService.InputBegan:Connect(function(input, processed) + if open and not processed and not drag and isPointer(input) then + dragging = true + end +end) +UserInputService.InputEnded:Connect(function(input) + if isPointer(input) then + dragging = false + end +end) +UserInputService.InputChanged:Connect(function(input) + if open and dragging and (input.UserInputType == Enum.UserInputType.MouseMovement or input.UserInputType == Enum.UserInputType.Touch) then + orbit -= input.Delta.X * 0.008 + end +end) + +RunService.RenderStepped:Connect(function(dt) + if not open then + return + end + local model = displayModel() + local chassis = model and model.PrimaryPart + if not chassis then + return + end + if not dragging then + orbit += dt * 0.2 + end + camera.CameraType = Enum.CameraType.Scriptable + -- Багги смотрит на ворота (+Z) — начинаем облёт спереди-сбоку. + local center = chassis.Position + Vector3.new(0, 1, 0) + local angle = orbit + 0.6 + local eye = center + Vector3.new(math.sin(angle) * 17, 6, math.cos(angle) * 17) + -- Сдвигаем кадр вправо, чтобы багги не пряталась за панелью, и не пускаем камеру за стены: + -- у задней стены она прижимается к ней, а направление взгляда остаётся прежним. + local view = CFrame.lookAt(eye, center) * CFrame.new(5.5, 0, 0) + camera.CFrame = CFrame.new(insideRoom(view.Position)) * view.Rotation +end) diff --git a/Zombi/src/client/Gun.client.luau b/Zombi/src/client/Gun.client.luau new file mode 100644 index 0000000..fda7f12 --- /dev/null +++ b/Zombi/src/client/Gun.client.luau @@ -0,0 +1,332 @@ +-- Пушка за рулём: прицел за мышью, турель следит за прицелом, ЛКМ — огонь, шкала перегрева. +-- Темп и нагрев — у пушки из слота «Оружие» (атрибут Weapon у багги). Автоматы — трассеры, +-- пушка и ракетница — летящие снаряды (взрыв в точке попадания делает сервер). + +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 UserInputService = game:GetService("UserInputService") + +local Config = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("Config")) +local GunMath = require(ReplicatedStorage.Shared:WaitForChild("GunMath")) +local Remotes = ReplicatedStorage:WaitForChild("Remotes") + +local G = Config.Gun +local player = Players.LocalPlayer + +local TRACER_COLOR = Color3.fromRGB(255, 205, 100) +local WHITE = Color3.fromRGB(255, 255, 255) +local RED = Color3.fromRGB(255, 80, 60) + +-- ===== Интерфейс ===== + +local gui = Instance.new("ScreenGui") +gui.Name = "GunHUD" +gui.ResetOnSpawn = false +gui.IgnoreGuiInset = true -- координаты совпадают с GetMouseLocation +gui.Parent = player:WaitForChild("PlayerGui") + +-- Прицел за мышью: четыре штриха и кольцо +local crosshair = Instance.new("Frame") +crosshair.AnchorPoint = Vector2.new(0.5, 0.5) +crosshair.Size = UDim2.fromOffset(40, 40) +crosshair.BackgroundTransparency = 1 +crosshair.Visible = false +crosshair.Parent = gui + +local ticks = {} +for _, spec in { + { UDim2.new(0.5, 0, 0, 0), UDim2.fromOffset(2, 12), Vector2.new(0.5, 0) }, + { UDim2.new(0.5, 0, 1, 0), UDim2.fromOffset(2, 12), Vector2.new(0.5, 1) }, + { UDim2.new(0, 0, 0.5, 0), UDim2.fromOffset(12, 2), Vector2.new(0, 0.5) }, + { UDim2.new(1, 0, 0.5, 0), UDim2.fromOffset(12, 2), Vector2.new(1, 0.5) }, +} do + local tick = Instance.new("Frame") + tick.Position = spec[1] + tick.Size = spec[2] + tick.AnchorPoint = spec[3] + tick.BorderSizePixel = 0 + tick.BackgroundColor3 = WHITE + tick.Parent = crosshair + table.insert(ticks, tick) +end +local ring = Instance.new("Frame") +ring.AnchorPoint = Vector2.new(0.5, 0.5) +ring.Position = UDim2.fromScale(0.5, 0.5) +ring.Size = UDim2.fromOffset(18, 18) +ring.BackgroundTransparency = 1 +ring.Parent = crosshair +Instance.new("UICorner", ring).CornerRadius = UDim.new(1, 0) +local ringStroke = Instance.new("UIStroke", ring) +ringStroke.Color = WHITE +ringStroke.Thickness = 1.5 + +-- Точка, куда реально летят пули (турель поворачивается не на все 360°) +local hitDot = Instance.new("Frame") +hitDot.AnchorPoint = Vector2.new(0.5, 0.5) +hitDot.Size = UDim2.fromOffset(6, 6) +hitDot.BackgroundColor3 = TRACER_COLOR +hitDot.BorderSizePixel = 0 +hitDot.Visible = false +hitDot.Parent = gui +Instance.new("UICorner", hitDot).CornerRadius = UDim.new(1, 0) + +-- Шкала перегрева над спидометром +local heatFrame = Instance.new("Frame") +heatFrame.AnchorPoint = Vector2.new(0.5, 1) +heatFrame.Position = UDim2.new(0.5, 0, 1, -132) +heatFrame.Size = UDim2.fromOffset(260, 22) +heatFrame.BackgroundTransparency = 1 +heatFrame.Visible = false +heatFrame.Parent = gui + +local heatTrack = Instance.new("Frame") +heatTrack.Position = UDim2.fromOffset(0, 14) +heatTrack.Size = UDim2.new(1, 0, 0, 8) +heatTrack.BackgroundColor3 = Color3.fromRGB(30, 22, 16) +heatTrack.BackgroundTransparency = 0.2 +heatTrack.Parent = heatFrame +Instance.new("UICorner", heatTrack).CornerRadius = UDim.new(1, 0) + +local heatFill = Instance.new("Frame") +heatFill.Size = UDim2.fromScale(0, 1) +heatFill.BackgroundColor3 = TRACER_COLOR +heatFill.Parent = heatTrack +Instance.new("UICorner", heatFill).CornerRadius = UDim.new(1, 0) + +local heatLabel = Instance.new("TextLabel") +heatLabel.Size = UDim2.new(1, 0, 0, 14) +heatLabel.BackgroundTransparency = 1 +heatLabel.Font = Enum.Font.GothamBold +heatLabel.TextSize = 12 +heatLabel.TextColor3 = Color3.fromRGB(230, 210, 190) +heatLabel.Text = "" +heatLabel.Parent = heatFrame + +-- ===== Эффекты ===== + +local function drawTracer(from: Vector3, to: Vector3) + local distance = (to - from).Magnitude + if distance < 0.5 then + return + end + local tracer = Instance.new("Part") + tracer.Anchored = true + tracer.CanCollide = false + tracer.CanQuery = false + tracer.CanTouch = false + tracer.CastShadow = false + tracer.Material = Enum.Material.Neon + tracer.Color = TRACER_COLOR + tracer.Size = Vector3.new(0.12, 0.12, distance) + tracer.CFrame = CFrame.lookAt(from, to) * CFrame.new(0, 0, -distance / 2) + tracer.Parent = workspace + Debris:AddItem(tracer, 0.05) + + local spark = Instance.new("Part") + spark.Anchored = true + spark.CanCollide = false + spark.CanQuery = false + spark.CanTouch = false + spark.Material = Enum.Material.Neon + spark.Color = Color3.fromRGB(255, 240, 180) + spark.Shape = Enum.PartType.Ball + spark.Size = Vector3.new(0.7, 0.7, 0.7) + spark.Position = to + spark.Parent = workspace + Debris:AddItem(spark, 0.08) +end + +local function muzzleFlash(model: Instance?) + local flash = model and model:FindFirstChild("MuzzleFlash") + if not flash then + return + end + flash.Transparency = 0.15 + local light = flash:FindFirstChildOfClass("PointLight") + if light then + light.Enabled = true + end + task.delay(0.04, function() + flash.Transparency = 1 + if light then + light.Enabled = false + end + end) +end + +local function weaponOf(model: Instance?) + local item = model and Config.PartById[model:GetAttribute("Weapon") or ""] or Config.PartById.mg_light + return item, item.gun +end + +local function effect(props): BasePart + local p = Instance.new("Part") + p.Anchored = true + p.CanCollide = false + p.CanQuery = false + p.CanTouch = false + p.CastShadow = false + for k, v in props do + p[k] = v + end + p.Parent = workspace + return p +end + +-- Летящий снаряд: от ствола до точки попадания за время полёта (там сервер устраивает взрыв). +local function drawProjectile(from: Vector3, to: Vector3, spec) + local distance = (to - from).Magnitude + if distance < 0.5 then + return + end + local time = distance / spec.speed + local aim = CFrame.lookAt(from, to) + local shell + if spec.kind == "rocket" then + shell = effect({ Size = Vector3.new(0.35, 0.35, 1.4), CFrame = aim, Color = Color3.fromRGB(80, 85, 70), Material = Enum.Material.Metal }) + local fire = Instance.new("Fire") + fire.Size = 2 + fire.Heat = 0 + fire.Parent = shell + local smoke = Instance.new("Smoke") + smoke.Color = Color3.fromRGB(120, 120, 120) + smoke.Opacity = 0.3 + smoke.Size = 1.5 + smoke.RiseVelocity = 0 + smoke.Parent = shell + else + shell = effect({ Shape = Enum.PartType.Ball, Size = Vector3.new(0.6, 0.6, 0.6), CFrame = aim, Color = Color3.fromRGB(255, 190, 90), Material = Enum.Material.Neon }) + end + TweenService:Create(shell, TweenInfo.new(time, Enum.EasingStyle.Linear), { CFrame = CFrame.lookAt(to, to + aim.LookVector) }):Play() + Debris:AddItem(shell, time + 0.05) +end + +local function drawShot(model: Instance?, from: Vector3, to: Vector3) + local _, spec = weaponOf(model) + if spec.kind == "bullet" then + drawTracer(from, to) + else + drawProjectile(from, to, spec) + end + muzzleFlash(model) +end + +-- Чужие выстрелы рисуем по сообщению сервера, свои — сразу, без задержки. +Remotes:WaitForChild("Tracer").OnClientEvent:Connect(function(model, from, to, shooterId) + if shooterId ~= player.UserId then + drawShot(model, from, to) + end +end) + +-- ===== Стрельба ===== + +local firing = false +local heat, overheated = 0, false +local lastShot, lastAimSent = 0, 0 +local twinSide = 1 + +UserInputService.InputBegan:Connect(function(input, processed) + if input.UserInputType == Enum.UserInputType.MouseButton1 and not processed then + firing = true + end +end) +UserInputService.InputEnded:Connect(function(input) + if input.UserInputType == Enum.UserInputType.MouseButton1 then + firing = false + end +end) + +local function drivenBuggy(): Model? + local character = player.Character + local humanoid = character and character:FindFirstChildOfClass("Humanoid") + local seat = humanoid and humanoid.SeatPart + if seat and seat:IsA("VehicleSeat") and seat.Name == "DriverSeat" then + return seat.Parent + end + return nil +end + +RunService.RenderStepped:Connect(function(dt) + -- Остывание (сервер считает так же и решает окончательно) + heat = math.max(heat - dt * G.CoolRate, 0) + if overheated and heat <= G.CoolResume then + overheated = false + end + + local model = drivenBuggy() + local chassis = model and model.PrimaryPart + local driving = chassis ~= nil + crosshair.Visible = driving + hitDot.Visible = false + heatFrame.Visible = driving + UserInputService.MouseIconEnabled = not driving + if not driving then + return + end + + local camera = workspace.CurrentCamera + local mouse = UserInputService:GetMouseLocation() + crosshair.Position = UDim2.fromOffset(mouse.X, mouse.Y) + + local params = RaycastParams.new() + params.FilterType = Enum.RaycastFilterType.Exclude + params.FilterDescendantsInstances = { model, player.Character } + + -- Куда смотрит прицел + local ray = camera:ViewportPointToRay(mouse.X, mouse.Y) + local aimHit = workspace:Raycast(ray.Origin, ray.Direction * 1000, params) + local target = aimHit and aimHit.Position or ray.Origin + ray.Direction * 1000 + + -- Поворачиваем турель (локально — сразу, на сервер — 10 раз в секунду) + local mount = (chassis.CFrame * GunMath.Mount).Position + local yaw, pitch, inSector = GunMath.Angles(chassis.CFrame, target - mount) + local motor = chassis:FindFirstChild("GunMotor") + if motor then + motor.C0 = GunMath.Mount * GunMath.Rotation(yaw, pitch) + end + local now = os.clock() + if now - lastAimSent > 0.1 then + lastAimSent = now + Remotes.AimGun:FireServer(yaw, pitch) + end + + -- Куда реально прилетят пули + local turret = GunMath.Turret(chassis.CFrame, yaw, pitch) + local origin = (turret * GunMath.Muzzle).Position + local shot = workspace:Raycast(origin, turret.LookVector * G.Range, params) + local impact = shot and shot.Position or origin + turret.LookVector * G.Range + local screen, onScreen = camera:WorldToViewportPoint(impact) + hitDot.Visible = onScreen + hitDot.Position = UDim2.fromOffset(screen.X, screen.Y) + + -- Прицел краснеет, если цель вне сектора турели или пулемёт перегрет + local color = (inSector and not overheated) and WHITE or RED + for _, tick in ticks do + tick.BackgroundColor3 = color + end + ringStroke.Color = color + + local item, spec = weaponOf(model) + heatFill.Size = UDim2.fromScale(math.clamp(heat, 0, 1), 1) + 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 + lastShot = now + heat += spec.heatPerShot + if heat >= 1 then + overheated = true + end + Remotes.FireGun:FireServer(target) + -- У спаренных стволы бьют по очереди: смещаем вспышку то влево, то вправо. + local from = origin + if spec.twin then + twinSide = -twinSide + from += turret.RightVector * 0.34 * twinSide + end + drawShot(model, from, impact) + end +end) diff --git a/Zombi/src/client/Health.client.luau b/Zombi/src/client/Health.client.luau new file mode 100644 index 0000000..b79fa2e --- /dev/null +++ b/Zombi/src/client/Health.client.luau @@ -0,0 +1,147 @@ +-- Здоровье игрока на карте команды: полоса HP сверху по центру. При уроне полоса сначала оставляет +-- светлый «след» потерянного здоровья, который догоняет её через мгновение, а края экрана вспыхивают красным. + +local Players = game:GetService("Players") +local TweenService = game:GetService("TweenService") + +local player = Players.LocalPlayer + +local BG = Color3.fromRGB(30, 22, 16) +local RED = Color3.fromRGB(215, 50, 40) +local GREEN = Color3.fromRGB(110, 200, 70) +local TEXT = Color3.fromRGB(245, 235, 220) + +local gui = Instance.new("ScreenGui") +gui.Name = "HealthHUD" +gui.ResetOnSpawn = false +gui.IgnoreGuiInset = true +gui.Parent = player:WaitForChild("PlayerGui") + +-- Красная вспышка по краям экрана при уроне +local vignette = Instance.new("Frame") +vignette.Size = UDim2.fromScale(1, 1) +vignette.BackgroundColor3 = RED +vignette.BackgroundTransparency = 1 +vignette.BorderSizePixel = 0 +vignette.Parent = gui +local vignetteGradient = Instance.new("UIGradient", vignette) +-- Прозрачно в центре, плотнее к левому и правому краю (радиального градиента в Roblox нет) +vignetteGradient.Transparency = NumberSequence.new({ + NumberSequenceKeypoint.new(0, 0.2), + NumberSequenceKeypoint.new(0.25, 1), + NumberSequenceKeypoint.new(0.75, 1), + NumberSequenceKeypoint.new(1, 0.2), +}) + +local bar = Instance.new("Frame") +bar.AnchorPoint = Vector2.new(0.5, 0) +bar.Position = UDim2.new(0.5, 0, 0, 14) +bar.Size = UDim2.fromOffset(340, 34) +bar.BackgroundColor3 = BG +bar.BackgroundTransparency = 0.1 +bar.Visible = false +bar.Parent = gui +Instance.new("UICorner", bar).CornerRadius = UDim.new(0, 10) +local barStroke = Instance.new("UIStroke", bar) +barStroke.Color = Color3.fromRGB(150, 90, 40) +barStroke.Thickness = 2 + +local track = Instance.new("Frame") +track.Position = UDim2.fromOffset(40, 9) +track.Size = UDim2.new(1, -52, 0, 16) +track.BackgroundColor3 = Color3.fromRGB(55, 40, 32) +track.BorderSizePixel = 0 +track.ClipsDescendants = true +track.Parent = bar +Instance.new("UICorner", track).CornerRadius = UDim.new(1, 0) + +local trail = Instance.new("Frame") -- «след» потерянного здоровья +trail.Size = UDim2.fromScale(1, 1) +trail.BackgroundColor3 = Color3.fromRGB(255, 230, 200) +trail.BorderSizePixel = 0 +trail.Parent = track +Instance.new("UICorner", trail).CornerRadius = UDim.new(1, 0) + +local fill = Instance.new("Frame") +fill.Size = UDim2.fromScale(1, 1) +fill.BackgroundColor3 = GREEN +fill.BorderSizePixel = 0 +fill.Parent = track +Instance.new("UICorner", fill).CornerRadius = UDim.new(1, 0) + +local icon = Instance.new("TextLabel") +icon.BackgroundTransparency = 1 +icon.Position = UDim2.fromOffset(8, 0) +icon.Size = UDim2.fromOffset(28, 34) +icon.Font = Enum.Font.GothamBlack +icon.TextSize = 20 +icon.Text = "❤" +icon.TextColor3 = RED +icon.Parent = bar + +local valueLabel = Instance.new("TextLabel") +valueLabel.BackgroundTransparency = 1 +valueLabel.Position = UDim2.fromOffset(40, 0) +valueLabel.Size = UDim2.new(1, -52, 1, 0) +valueLabel.Font = Enum.Font.GothamBlack +valueLabel.TextSize = 15 +valueLabel.TextColor3 = TEXT +valueLabel.TextStrokeTransparency = 0.4 +valueLabel.ZIndex = 2 +valueLabel.Parent = bar + +local function inBattle(): boolean + return (player:GetAttribute("Arena") or 0) > 0 +end + +local humanoid: Humanoid? = nil +local lastHealth = 0 + +local function render(health: number, maxHealth: number, hurt: boolean) + local ratio = math.clamp(health / math.max(maxHealth, 1), 0, 1) + valueLabel.Text = ("%d / %d"):format(math.ceil(health), maxHealth) + -- Цвет от зелёного к красному по мере убывания + local color = RED:Lerp(GREEN, math.clamp((ratio - 0.2) / 0.6, 0, 1)) + TweenService:Create(fill, TweenInfo.new(0.12), { Size = UDim2.fromScale(ratio, 1), BackgroundColor3 = color }):Play() + if hurt then + -- След догоняет с задержкой, экран вспыхивает, иконка дёргается + task.delay(0.35, function() + TweenService:Create(trail, TweenInfo.new(0.4, Enum.EasingStyle.Quad), { Size = UDim2.fromScale(ratio, 1) }):Play() + end) + vignette.BackgroundTransparency = 0.55 + TweenService:Create(vignette, TweenInfo.new(0.5), { BackgroundTransparency = 1 }):Play() + icon.TextSize = 28 + TweenService:Create(icon, TweenInfo.new(0.25, Enum.EasingStyle.Back), { TextSize = 20 }):Play() + else + trail.Size = UDim2.fromScale(ratio, 1) + end +end + +local function watch(character: Model) + local h = character:WaitForChild("Humanoid", 10) :: Humanoid? + if not h then + return + end + humanoid = h + lastHealth = h.Health + render(h.Health, h.MaxHealth, false) + h.HealthChanged:Connect(function(health) + if humanoid ~= h then + return + end + local hurt = health < lastHealth - 0.5 and inBattle() + lastHealth = health + render(health, h.MaxHealth, hurt) + end) +end + +local function refreshVisible() + bar.Visible = inBattle() +end + +player.CharacterAdded:Connect(watch) +if player.Character then + task.spawn(watch, player.Character) +end +player:GetAttributeChangedSignal("Arena"):Connect(refreshVisible) +refreshVisible() diff --git a/Zombi/src/client/Lobby.client.luau b/Zombi/src/client/Lobby.client.luau new file mode 100644 index 0000000..69838f9 --- /dev/null +++ b/Zombi/src/client/Lobby.client.luau @@ -0,0 +1,305 @@ +-- Меню лобби в ангаре: появляется, когда игрок стоит в круге или состоит в лобби. +-- Пустой круг — «Создать лобби» и выбор, сколько будет игроков (1–4); круг с лобби — «Вступить». +-- Создатель меняет размер (не меньше, чем уже в лобби) и может закрыть лобби, остальные — покинуть. +-- Пока игрок в лобби, стенки его круга для него твёрдые. На карте команды — кнопка «В ангар». + +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") + +local Config = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("Config")) +local Remotes = ReplicatedStorage:WaitForChild("Remotes") +local ActionRemote = Remotes:WaitForChild("LobbyAction") + +local L = Config.Lobby +local player = Players.LocalPlayer +local lobbies = workspace:WaitForChild("Lobbies") + +local BG = Color3.fromRGB(30, 22, 16) +local CARD = Color3.fromRGB(52, 40, 30) +local ACCENT = Color3.fromRGB(150, 90, 40) +local ORANGE = Color3.fromRGB(230, 130, 40) +local TEXT = Color3.fromRGB(235, 220, 200) +local MUTED = Color3.fromRGB(170, 150, 130) +local DISABLED = Color3.fromRGB(40, 34, 30) +local WHITE = Color3.fromRGB(255, 255, 255) + +-- ===== Интерфейс ===== + +local gui = Instance.new("ScreenGui") +gui.Name = "LobbyHUD" +gui.ResetOnSpawn = false +gui.Parent = player:WaitForChild("PlayerGui") + +local panel = Instance.new("Frame") +panel.AnchorPoint = Vector2.new(0.5, 1) +panel.Position = UDim2.new(0.5, 0, 1, -24) +panel.Size = UDim2.fromOffset(340, 0) +panel.AutomaticSize = Enum.AutomaticSize.Y +panel.BackgroundColor3 = BG +panel.BackgroundTransparency = 0.1 +panel.Visible = false +panel.Parent = gui +Instance.new("UICorner", panel).CornerRadius = UDim.new(0, 14) +local panelStroke = Instance.new("UIStroke", panel) +panelStroke.Thickness = 2 +local padding = Instance.new("UIPadding", panel) +padding.PaddingTop = UDim.new(0, 14) +padding.PaddingBottom = UDim.new(0, 14) +padding.PaddingLeft = UDim.new(0, 16) +padding.PaddingRight = UDim.new(0, 16) +local layout = Instance.new("UIListLayout", panel) +layout.SortOrder = Enum.SortOrder.LayoutOrder +layout.Padding = UDim.new(0, 8) + +local returnButton = Instance.new("TextButton") +returnButton.AnchorPoint = Vector2.new(1, 0) +returnButton.Position = UDim2.new(1, -16, 0, 60) +returnButton.Size = UDim2.fromOffset(150, 40) +returnButton.BackgroundColor3 = BG +returnButton.BackgroundTransparency = 0.1 +returnButton.Font = Enum.Font.GothamBlack +returnButton.TextSize = 16 +returnButton.TextColor3 = ORANGE +returnButton.Text = "В АНГАР" +returnButton.Visible = false +returnButton.Parent = gui +Instance.new("UICorner", returnButton).CornerRadius = UDim.new(0, 10) +local returnStroke = Instance.new("UIStroke", returnButton) +returnStroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border +returnStroke.Color = ACCENT +returnStroke.Thickness = 2 +returnButton.Activated:Connect(function() + ActionRemote:FireServer("return") +end) + +local order = 0 +local function label(text: string, size: number, color: Color3, font: Enum.Font?): TextLabel + order += 1 + local l = Instance.new("TextLabel") + l.LayoutOrder = order + l.BackgroundTransparency = 1 + l.Size = UDim2.new(1, 0, 0, 0) + l.AutomaticSize = Enum.AutomaticSize.Y + l.Font = font or Enum.Font.GothamBold + l.TextSize = size + l.TextColor3 = color + l.TextWrapped = true + l.TextXAlignment = Enum.TextXAlignment.Left + l.Text = text + l.Parent = panel + return l +end + +local function row(height: number): Frame + order += 1 + local f = Instance.new("Frame") + f.LayoutOrder = order + f.BackgroundTransparency = 1 + f.Size = UDim2.new(1, 0, 0, height) + f.Parent = panel + local l = Instance.new("UIListLayout", f) + l.FillDirection = Enum.FillDirection.Horizontal + l.Padding = UDim.new(0, 6) + return f +end + +local function button(parent: Instance, text: string, width: number, height: number, color: Color3, onClick: (() -> ())?): TextButton + local b = Instance.new("TextButton") + b.Size = UDim2.fromOffset(width, height) + b.BackgroundColor3 = color + b.AutoButtonColor = onClick ~= nil + b.Font = Enum.Font.GothamBold + b.TextSize = 15 + b.TextColor3 = if onClick then TEXT else MUTED + b.Text = text + b.Parent = parent + Instance.new("UICorner", b).CornerRadius = UDim.new(0, 8) + local stroke = Instance.new("UIStroke", b) + stroke.ApplyStrokeMode = Enum.ApplyStrokeMode.Border + stroke.Color = WHITE + stroke.Thickness = 0 + if onClick then + b.Activated:Connect(onClick) + end + return b +end + +-- Широкая кнопка главного действия +local function bigButton(text: string, color: Color3, onClick: () -> ()) + local b = button(row(44), text, 308, 44, color, onClick) + b.Font = Enum.Font.GothamBlack + b.TextSize = 17 + if color == ORANGE then + b.TextColor3 = BG + end +end + +-- Ряд кнопок 1..MaxPlayers. minimum — меньше нельзя, selected — обведён. +local function sizeButtons(minimum: number, selected: number?, onPick: (number) -> ()) + local container = row(44) + local width = (308 - 6 * (L.MaxPlayers - 1)) / L.MaxPlayers + for n = 1, L.MaxPlayers do + local allowed = n >= minimum + local b = button(container, tostring(n), width, 44, if allowed then CARD else DISABLED, if allowed then function() + onPick(n) + end else nil) + b.Font = Enum.Font.GothamBlack + b.TextSize = 20 + if n == selected then + b.BackgroundColor3 = ACCENT + b:FindFirstChildOfClass("UIStroke").Thickness = 3 + end + end +end + +-- ===== Состояние ===== + +local choosing = false -- после «Создать лобби» показываем выбор количества игроков +local choosingIn = 0 +local countdown: TextLabel? = nil +local countdownModel: Model? = nil + +local function circle(index: number): Model? + return lobbies:FindFirstChild("Lobby" .. index) :: Model? +end + +local function membersText(model: Model): string + local names = model:GetAttribute("Members") or "" + return (names:gsub("\n", " · ")) +end + +-- Стенки своего круга — твёрдые, пока игрок в лобби (меняем только у себя на клиенте). +local function updateWalls() + local memberIndex = player:GetAttribute("Lobby") or 0 + for _, model in lobbies:GetChildren() do + local walls = model:FindFirstChild("Walls") + if walls then + local solid = model:GetAttribute("Index") == memberIndex and model:GetAttribute("Status") ~= "playing" + for _, wall in walls:GetChildren() do + wall.CanCollide = solid + end + end + end +end + +local function render() + for _, child in panel:GetChildren() do + if not child:IsA("UIComponent") then + child:Destroy() + end + end + order = 0 + countdown, countdownModel = nil, nil + updateWalls() + + local memberIndex = player:GetAttribute("Lobby") or 0 + local standIndex = player:GetAttribute("LobbyIn") or 0 + local arena = player:GetAttribute("Arena") or 0 + returnButton.Visible = arena > 0 + + local index = if memberIndex > 0 then memberIndex else standIndex + local model = if index > 0 then circle(index) else nil + if arena > 0 or not model then + panel.Visible = false + choosing = false + return + end + panel.Visible = true + panelStroke.Color = L.Colors[index] or ACCENT + + local status = model:GetAttribute("Status") + local size = model:GetAttribute("Size") or 0 + local count = model:GetAttribute("Count") or 0 + local ownerName = model:GetAttribute("OwnerName") or "" + if choosingIn ~= standIndex or status ~= "free" or memberIndex > 0 then + choosing = false + end + + if memberIndex > 0 then + local isOwner = model:GetAttribute("OwnerId") == player.UserId + label(if isOwner then "ТВОЁ ЛОББИ" else "ЛОББИ · " .. string.upper(ownerName), 22, ORANGE, Enum.Font.GothamBlack) + label(("Игроков %d / %d: %s"):format(count, size, membersText(model)), 14, TEXT) + if status == "starting" then + countdown = label("", 16, ORANGE, Enum.Font.GothamBlack) + countdownModel = model + end + if isOwner then + label("Сколько будет игроков", 13, MUTED, Enum.Font.GothamMedium) + sizeButtons(count, size, function(n) + ActionRemote:FireServer("size", n) + end) + bigButton("ЗАКРЫТЬ ЛОББИ", CARD, function() + ActionRemote:FireServer("close") + end) + else + bigButton("ПОКИНУТЬ ЛОББИ", CARD, function() + ActionRemote:FireServer("leave") + end) + end + label("Пока ты в лобби, из круга не выйти", 12, MUTED, Enum.Font.GothamMedium) + elseif status == "free" then + if choosing then + label("НОВОЕ ЛОББИ", 22, ORANGE, Enum.Font.GothamBlack) + label("Сколько будет игроков?", 14, TEXT) + sizeButtons(1, nil, function(n) + choosing = false + ActionRemote:FireServer("create", n) + end) + bigButton("Отмена", CARD, function() + choosing = false + render() + end) + else + label("ЛОББИ " .. index, 22, ORANGE, Enum.Font.GothamBlack) + label("Круг свободен — собери свою команду", 14, TEXT) + bigButton("СОЗДАТЬ ЛОББИ", ORANGE, function() + choosing, choosingIn = true, standIndex + render() + end) + end + elseif status == "open" then + label("ЛОББИ · " .. string.upper(ownerName), 22, ORANGE, Enum.Font.GothamBlack) + label(("Игроков %d / %d: %s"):format(count, size, membersText(model)), 14, TEXT) + bigButton("ВСТУПИТЬ В ЛОББИ", ORANGE, function() + ActionRemote:FireServer("join") + end) + elseif status == "starting" then + label("ЛОББИ · " .. string.upper(ownerName), 22, ORANGE, Enum.Font.GothamBlack) + label("Лобби заполнено — команда уже выезжает", 14, TEXT) + else + label("ЛОББИ " .. index, 22, ORANGE, Enum.Font.GothamBlack) + label("Команда этого круга сейчас на своей карте. Круг освободится, когда все вернутся.", 14, TEXT) + end +end + +-- ===== Подписки ===== + +for _, attribute in { "Lobby", "LobbyIn", "Arena" } do + player:GetAttributeChangedSignal(attribute):Connect(render) +end + +local function watchCircle(model: Instance) + model.AttributeChanged:Connect(render) + -- При StreamingEnabled стенки могут подгрузиться позже модели. + model.DescendantAdded:Connect(function(d) + if d:IsA("BasePart") and d.Name == "Wall" then + updateWalls() + end + end) +end +for _, model in lobbies:GetChildren() do + watchCircle(model) +end +lobbies.ChildAdded:Connect(function(model) + watchCircle(model) + render() +end) +render() + +RunService.Heartbeat:Connect(function() + if countdown and countdownModel then + local left = (countdownModel:GetAttribute("StartAt") or 0) - workspace:GetServerTimeNow() + countdown.Text = if left > 0 then ("Старт через %d…"):format(math.ceil(left)) else "Готовим карту…" + end +end) diff --git a/Zombi/src/client/ZombieFX.client.luau b/Zombi/src/client/ZombieFX.client.luau new file mode 100644 index 0000000..319a5d3 --- /dev/null +++ b/Zombi/src/client/ZombieFX.client.luau @@ -0,0 +1,128 @@ +-- Эффекты попаданий по зомби (сигнал ZombieHit от сервера): вылетающая цифра урона, искры, +-- зелёные брызги и короткая вспышка. Убийство — крупная надпись и взрыв брызг. + +local Debris = game:GetService("Debris") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local TweenService = game:GetService("TweenService") + +local Remotes = ReplicatedStorage:WaitForChild("Remotes") +local HitRemote = Remotes:WaitForChild("ZombieHit") + +local rng = Random.new() + +local MAX_DISTANCE = 300 -- дальше эффекты не рисуем — их всё равно не видно + +local function anchor(position: Vector3): Part + local p = Instance.new("Part") + p.Anchored = true + p.CanCollide = false + p.CanQuery = false + p.CanTouch = false + p.Transparency = 1 + p.Size = Vector3.new(0.2, 0.2, 0.2) + p.Position = position + p.Parent = workspace + return p +end + +-- Цвет цифры: мелкий урон — жёлтый, средний — оранжевый, крупный — красный. +local function damageColor(amount: number): Color3 + if amount >= 30 then + return Color3.fromRGB(255, 60, 50) + elseif amount >= 12 then + return Color3.fromRGB(255, 140, 40) + end + return Color3.fromRGB(255, 225, 80) +end + +-- Цифра «−12»: выскакивает с пружинкой, взлетает в сторону и гаснет. +local function floatingText(position: Vector3, text: string, color: Color3, size: number, life: number) + local holder = anchor(position + Vector3.new(rng:NextNumber(-0.8, 0.8), 0.6, rng:NextNumber(-0.8, 0.8))) + local gui = Instance.new("BillboardGui") + gui.Size = UDim2.fromScale(size * 2.4, size) + gui.AlwaysOnTop = true + gui.LightInfluence = 0 + gui.MaxDistance = MAX_DISTANCE + gui.Parent = holder + local label = Instance.new("TextLabel") + label.AnchorPoint = Vector2.new(0.5, 0.5) + label.Position = UDim2.fromScale(0.5, 0.5) + label.Size = UDim2.fromScale(0.3, 0.3) + label.BackgroundTransparency = 1 + label.Font = Enum.Font.GothamBlack + label.TextScaled = true + label.TextColor3 = color + label.TextStrokeColor3 = Color3.fromRGB(30, 10, 5) + label.TextStrokeTransparency = 0 + label.Rotation = rng:NextNumber(-12, 12) + label.Text = text + label.Parent = gui + + -- Пружинка: быстро раздувается больше нормы и садится обратно. + TweenService:Create(label, TweenInfo.new(0.12, Enum.EasingStyle.Back, Enum.EasingDirection.Out), { Size = UDim2.fromScale(1.15, 1.15) }):Play() + task.delay(0.12, function() + TweenService:Create(label, TweenInfo.new(0.15), { Size = UDim2.fromScale(1, 1) }):Play() + end) + -- Взлёт вбок и затухание + local drift = Vector3.new(rng:NextNumber(-2.5, 2.5), rng:NextNumber(3.5, 5), rng:NextNumber(-2.5, 2.5)) + TweenService:Create(holder, TweenInfo.new(life, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), { Position = holder.Position + drift }):Play() + task.delay(life * 0.55, function() + TweenService:Create(label, TweenInfo.new(life * 0.45), { TextTransparency = 1, TextStrokeTransparency = 1 }):Play() + end) + Debris:AddItem(holder, life + 0.1) +end + +local function burst(holder: BasePart, props, count: number) + local attachment = Instance.new("Attachment") + attachment.Parent = holder + local emitter = Instance.new("ParticleEmitter") + emitter.Enabled = false + emitter.SpreadAngle = Vector2.new(180, 180) + for k, v in props do + emitter[k] = v + end + emitter.Parent = attachment + emitter:Emit(count) +end + +-- Искры, зелёные брызги и вспышка света. big — убийство: всего больше. +local function impact(position: Vector3, big: boolean) + local holder = anchor(position) + local scale = if big then 2 else 1 + burst(holder, { + Color = ColorSequence.new(Color3.fromRGB(255, 240, 160), Color3.fromRGB(255, 120, 30)), + LightEmission = 1, + Size = NumberSequence.new(0.35, 0), + Lifetime = NumberRange.new(0.15, 0.35), + Speed = NumberRange.new(14, 30), + Drag = 4, + }, 14 * scale) + burst(holder, { + Color = ColorSequence.new(Color3.fromRGB(120, 200, 60), Color3.fromRGB(50, 90, 30)), + LightEmission = 0.2, + Size = NumberSequence.new({ NumberSequenceKeypoint.new(0, 0.5), NumberSequenceKeypoint.new(1, 0.15) }), + Transparency = NumberSequence.new(0, 1), + Lifetime = NumberRange.new(0.4, 0.8), + Speed = NumberRange.new(6, 14), + Acceleration = Vector3.new(0, -40, 0), + }, 8 * scale) + local light = Instance.new("PointLight") + light.Color = Color3.fromRGB(255, 170, 70) + light.Range = 10 * scale + light.Brightness = 3 + light.Parent = holder + TweenService:Create(light, TweenInfo.new(0.2), { Brightness = 0 }):Play() + Debris:AddItem(holder, 1) +end + +HitRemote.OnClientEvent:Connect(function(position: Vector3, amount: number, killed: boolean) + local camera = workspace.CurrentCamera + if (camera.CFrame.Position - position).Magnitude > MAX_DISTANCE then + return + end + impact(position, killed) + floatingText(position, "−" .. amount, damageColor(amount), if amount >= 30 then 2.4 elseif amount >= 12 then 1.9 else 1.5, 0.9) + if killed then + floatingText(position + Vector3.new(0, 1.5, 0), "УБИТ!", Color3.fromRGB(255, 70, 60), 2.6, 1.3) + end +end) diff --git a/Zombi/src/first/Loading.client.luau b/Zombi/src/first/Loading.client.luau new file mode 100644 index 0000000..66b8385 --- /dev/null +++ b/Zombi/src/first/Loading.client.luau @@ -0,0 +1,337 @@ +-- Заставка загрузки (ReplicatedFirst — запускается раньше всего остального). +-- Показывается при входе в игру, после возрождения и при каждом переходе между зонами (по сигналу сервера, см. Loading): +-- полоса прогресса с процентами, этап загрузки и советы. Пока она на экране, управление персонажем выключено. +-- Уходит, только когда вокруг подгружены земля, детали, текстуры и свет, а сервер отпустил персонажа, — +-- после этого управление и камера возвращаются полностью. + +local ContentProvider = game:GetService("ContentProvider") +local Players = game:GetService("Players") +local ReplicatedFirst = game:GetService("ReplicatedFirst") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local TweenService = game:GetService("TweenService") + +local player = Players.LocalPlayer + +local BG = Color3.fromRGB(16, 12, 9) +local BG2 = Color3.fromRGB(58, 36, 20) +local ORANGE = Color3.fromRGB(230, 130, 40) +local HAZARD = Color3.fromRGB(220, 175, 40) +local TEXT = Color3.fromRGB(235, 220, 200) +local MUTED = Color3.fromRGB(170, 150, 130) +local TRACK = Color3.fromRGB(52, 40, 30) + +local PRELOAD_RADIUS = 220 +local MIN_TIME = 1.5 -- даже если всё уже загружено: даём движку обновить свет и тени +local MAX_TIME = 10 +local BAR_W = 440 + +local TIPS = { + "R — перевернуть багги. Застрял на крыше — через 5 секунд она встанет сама.", + "Бронелисты держат пули: попадание в броню не ранит водителя.", + "Колесо фортуны в ангаре можно крутить раз в 4 часа.", + "Детали в гараже перетаскиваются в слот своего цвета.", + "На карту выезжают только командой — через круги лобби в ангаре.", + "Гусеницы цепче колёс, но медленнее.", + "Взрывающиеся бочки — отличная ловушка для врага.", +} + +-- ===== Заставка ===== + +local gui = Instance.new("ScreenGui") +gui.Name = "LoadingScreen" +gui.ResetOnSpawn = false +gui.IgnoreGuiInset = true +gui.DisplayOrder = 1000 +gui.Parent = player:WaitForChild("PlayerGui") + +-- CanvasGroup — чтобы плавно гасить всю заставку разом. +local cover = Instance.new("CanvasGroup") +cover.Size = UDim2.fromScale(1, 1) +cover.BackgroundColor3 = BG +cover.BorderSizePixel = 0 +cover.Active = true -- клики не проходят сквозь заставку +cover.Parent = gui +-- Фон отдельной рамкой: градиент на самой CanvasGroup перекрасил бы и текст. +local background = Instance.new("Frame") +background.Size = UDim2.fromScale(1, 1) +background.BackgroundColor3 = Color3.new(1, 1, 1) +background.BorderSizePixel = 0 +background.Parent = cover +local gradient = Instance.new("UIGradient") +gradient.Color = ColorSequence.new(BG, BG2) +gradient.Rotation = 115 +gradient.Parent = background + +local function text(props): TextLabel + local l = Instance.new("TextLabel") + l.AnchorPoint = Vector2.new(0.5, 0.5) + l.BackgroundTransparency = 1 + l.TextWrapped = true + for k, v in props do + l[k] = v + end + l.Parent = cover + return l +end + +text({ Position = UDim2.fromScale(0.5, 0.3), Size = UDim2.fromOffset(600, 24), Font = Enum.Font.GothamBlack, TextSize = 18, TextColor3 = MUTED, Text = "APOCALYPSE BUGGY" }) +local title = text({ Position = UDim2.fromScale(0.5, 0.4), Size = UDim2.new(1, -40, 0, 56), Font = Enum.Font.GothamBlack, TextSize = 52, TextColor3 = ORANGE, Text = "ЗАГРУЗКА" }) + +-- Жёлто-чёрная полоса под названием зоны +local stripe = Instance.new("Frame") +stripe.AnchorPoint = Vector2.new(0.5, 0.5) +stripe.Position = UDim2.new(0.5, 0, 0.4, 40) +stripe.Size = UDim2.fromOffset(BAR_W, 6) +stripe.BackgroundColor3 = HAZARD +stripe.BorderSizePixel = 0 +stripe.ClipsDescendants = true +stripe.Parent = cover +for i = 0, BAR_W / 24 - 1 do + local dash = Instance.new("Frame") + dash.Position = UDim2.fromOffset(i * 24 + 12, 0) + dash.Size = UDim2.fromOffset(12, 6) + dash.BackgroundColor3 = BG + dash.BorderSizePixel = 0 + dash.Parent = stripe +end + +-- Полоса загрузки с процентами +local track = Instance.new("Frame") +track.AnchorPoint = Vector2.new(0.5, 0.5) +track.Position = UDim2.new(0.5, 0, 0.4, 104) +track.Size = UDim2.fromOffset(BAR_W, 14) +track.BackgroundColor3 = TRACK +track.BorderSizePixel = 0 +track.Parent = cover +Instance.new("UICorner", track).CornerRadius = UDim.new(1, 0) +local trackStroke = Instance.new("UIStroke", track) +trackStroke.Color = Color3.fromRGB(90, 66, 44) +trackStroke.Thickness = 1 +local bar = Instance.new("Frame") +bar.Size = UDim2.fromScale(0, 1) +bar.BackgroundColor3 = ORANGE +bar.BorderSizePixel = 0 +bar.Parent = track +Instance.new("UICorner", bar).CornerRadius = UDim.new(1, 0) +local barGradient = Instance.new("UIGradient", bar) +barGradient.Color = ColorSequence.new(HAZARD, ORANGE) + +local stage = text({ Position = UDim2.new(0.5, -BAR_W / 2, 0.4, 78), AnchorPoint = Vector2.new(0, 0.5), Size = UDim2.fromOffset(BAR_W - 60, 20), Font = Enum.Font.GothamMedium, TextSize = 15, TextColor3 = TEXT, TextXAlignment = Enum.TextXAlignment.Left, Text = "" }) +local percent = text({ Position = UDim2.new(0.5, BAR_W / 2, 0.4, 78), AnchorPoint = Vector2.new(1, 0.5), Size = UDim2.fromOffset(60, 20), Font = Enum.Font.GothamBlack, TextSize = 15, TextColor3 = ORANGE, TextXAlignment = Enum.TextXAlignment.Right, Text = "0%" }) +local tip = text({ Position = UDim2.new(0.5, 0, 1, -60), Size = UDim2.new(1, -60, 0, 44), Font = Enum.Font.GothamMedium, TextSize = 16, TextColor3 = MUTED, Text = "" }) + +local fadeInfo = TweenInfo.new(0.35, Enum.EasingStyle.Quad) +local shown = false + +local function setStage(label: string, value: number) + stage.Text = label + percent.Text = ("%d%%"):format(math.floor(math.clamp(value, 0, 1) * 100 + 0.5)) + TweenService:Create(bar, TweenInfo.new(0.25), { Size = UDim2.fromScale(math.clamp(value, 0, 1), 1) }):Play() +end + +local function randomTip() + tip.Text = "💡 " .. TIPS[math.random(1, #TIPS)] +end + +-- Советы меняются, пока заставка на экране. +task.spawn(function() + while true do + task.wait(4) + if shown then + randomTip() + end + end +end) + +-- ===== Управление персонажем ===== + +local controls = nil +local controlsWanted = true + +-- Модуль управления появляется не сразу (ReplicatedFirst запускается раньше PlayerScripts). +local function applyControls() + if not controls then + pcall(function() + local scripts = player:WaitForChild("PlayerScripts", 10) + local module = scripts and scripts:WaitForChild("PlayerModule", 10) + controls = module and require(module):GetControls() + end) + end + if controls then + if controlsWanted then + controls:Enable() + else + controls:Disable() + end + end +end + +local function setControls(enabled: boolean) + controlsWanted = enabled + task.spawn(applyControls) +end + +-- Вернуть персонажу управление и обычную камеру (меню гаража само переключит камеру, если оно открыто). +local function restoreControl() + setControls(true) + local character = player.Character + local humanoid = character and character:FindFirstChildOfClass("Humanoid") + local camera = workspace.CurrentCamera + if humanoid then + camera.CameraSubject = humanoid + end + if camera.CameraType ~= Enum.CameraType.Custom and not player:GetAttribute("InGarage") then + camera.CameraType = Enum.CameraType.Custom + end +end + +-- ===== Показ и скрытие ===== + +local busy = 0 -- номер текущей загрузки: новая отменяет скрытие старой + +local function show(zone: string, instant: boolean?): number + busy += 1 + shown = true + setControls(false) + title.Text = string.upper(zone) + setStage("Переезжаем…", 0) + randomTip() + gui.Enabled = true + if instant then + cover.GroupTransparency = 0 + else + local tween = TweenService:Create(cover, fadeInfo, { GroupTransparency = 0 }) + tween:Play() + tween.Completed:Wait() + end + return busy +end + +local function reveal(id: number) + if busy ~= id then + return -- уже началась следующая загрузка + end + setStage("Готово", 1) + restoreControl() + task.wait(0.25) + if busy ~= id then + return + end + shown = false + local tween = TweenService:Create(cover, fadeInfo, { GroupTransparency = 1 }) + tween:Play() + tween.Completed:Wait() + if busy == id then + gui.Enabled = false + end +end + +-- ===== Подгрузка сцены ===== + +local function rootPart(): BasePart? + local character = player.Character + return character and character:FindFirstChild("HumanoidRootPart") :: BasePart? +end + +-- Ждём землю под ногами (при StreamingEnabled она может прийти позже), грузим ассеты деталей вокруг, +-- даём устояться свету. +local function preloadAround(position: Vector3) + local started = os.clock() + local deadline = started + MAX_TIME + setStage("Подгружаем местность…", 0.08) + + local params = RaycastParams.new() + params.FilterType = Enum.RaycastFilterType.Exclude + params.FilterDescendantsInstances = { player.Character } + while os.clock() < deadline do + if workspace:Raycast(position + Vector3.new(0, 4, 0), Vector3.new(0, -60, 0), params) then + break + end + task.wait(0.1) + end + setStage("Текстуры и объекты…", 0.25) + + local parts = workspace:GetPartBoundsInRadius(position, PRELOAD_RADIUS) + local total = math.max(#parts, 1) + local done = 0 + local finished = false + task.spawn(function() + pcall(function() + ContentProvider:PreloadAsync(parts, function() + done += 1 + if done % 20 == 0 then + setStage("Текстуры и объекты…", 0.25 + 0.55 * done / total) + end + end) + end) + finished = true + end) + while not finished and os.clock() < deadline do + task.wait(0.05) + end + + setStage("Освещение…", 0.85) + task.wait(math.max(0.4, MIN_TIME - (os.clock() - started))) +end + +-- Сервер держит персонажа на месте, пока идёт загрузка, — ждём, когда отпустит. +local function waitReleased() + setStage("Почти готово…", 0.95) + local deadline = os.clock() + 4 + local root = rootPart() + while root and root.Anchored and os.clock() < deadline do + task.wait(0.05) + end +end + +-- ===== Вход в игру и возрождение ===== + +local function loadCharacterArea(zone: string, instant: boolean) + local id = show(zone, instant) + local character = player.Character or player.CharacterAdded:Wait() + character:WaitForChild("HumanoidRootPart", MAX_TIME) + local root = rootPart() + if root then + preloadAround(root.Position) + end + reveal(id) +end + +task.spawn(function() + show("Ангар", true) + pcall(function() + ReplicatedFirst:RemoveDefaultLoadingScreen() + end) + setStage("Соединение с сервером…", 0.02) + if not game:IsLoaded() then + game.Loaded:Wait() + end + loadCharacterArea("Ангар", true) +end) + +-- После возрождения персонаж появляется в ангаре — та же заставка. +local firstCharacter = player.Character == nil +player.CharacterAdded:Connect(function() + if firstCharacter then + firstCharacter = false + return + end + loadCharacterArea("Ангар", true) +end) + +-- ===== Переходы по сигналу сервера ===== + +local Remote = ReplicatedStorage:WaitForChild("Remotes"):WaitForChild("Loading") + +Remote.OnClientEvent:Connect(function(step, token, value) + if step == "show" then + show(tostring(value or ""), false) + Remote:FireServer("ready", token) + elseif step == "arrived" then + local id = busy + preloadAround(value) + Remote:FireServer("loaded", token) + waitReleased() + reveal(id) + end +end) diff --git a/Zombi/src/server/Buggy.luau b/Zombi/src/server/Buggy.luau new file mode 100644 index 0000000..7dc56a1 --- /dev/null +++ b/Zombi/src/server/Buggy.luau @@ -0,0 +1,672 @@ +-- Багги апокалипсиса на физике: рама, независимая подвеска на пружинах, полный привод, +-- поворотные передние колёса. Управление — с водительского VehicleSeat (WASD). + +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local RunService = game:GetService("RunService") + +local Config = require(ReplicatedStorage.Shared.Config) +local BuggyStats = require(ReplicatedStorage.Shared.BuggyStats) +local GunMath = require(ReplicatedStorage.Shared.GunMath) + +local B = Config.Buggy +local Buggy = {} + +local active = {} -- [Model] = { seat, chassis, motors, servos } + +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) + +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 }, +} + +local function newPart(model: Model, className: string, props): BasePart + local p = Instance.new(className) + p.Anchored = true + p.TopSurface = Enum.SurfaceType.Smooth + p.BottomSurface = Enum.SurfaceType.Smooth + for k, v in props do + p[k] = v + end + p.Parent = model + return p +end + +local function weld(a: BasePart, b: BasePart) + local w = Instance.new("WeldConstraint") + w.Part0 = a + w.Part1 = b + w.Parent = b +end + +local function attachment(parent: BasePart, localCFrame: CFrame, name: string): Attachment + local a = Instance.new("Attachment") + a.Name = name + a.CFrame = localCFrame + a.Parent = parent + return a +end + +local function pick(list, index) + return list[index] or list[1] +end + +-- Настройка из гаража: paint, accent — номера из Config.Garage.Paints/Accents; +-- front, wheels, rear, armor — id деталей из Config.Garage.Parts ("" — слот пуст). +function Buggy.DefaultSetup() + return { paint = 1, accent = 1, front = "spikes", wheels = "wheels_std", rear = "", armor = "", weapon = "mg_light" } +end + +-- Во сколько раз меняется максимальная скорость от установленных деталей (см. BuggyStats). +Buggy.SpeedFactor = BuggyStats.SpeedFactor + +-- groundCFrame — точка на земле, куда ставим багги (смотрит вперёд по -Z). +-- options: setup — тюнинг, owner — только он может сесть за руль, +-- display — неподвижная модель для витрины (гараж, разбитые багги в ангаре), parent. +function Buggy.Build(groundCFrame: CFrame, options): Model + options = options or {} + local setup = options.setup or Buggy.DefaultSetup() + local paint = pick(Config.Garage.Paints, setup.paint) + local accent = pick(Config.Garage.Accents, setup.accent) + local wheelSpec = Config.PartById[setup.wheels or ""] or Config.PartById.wheels_std + 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 + + 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 chassis = newPart(model, "Part", { + Name = "Chassis", + Size = Vector3.new(6, 1, 10), + CFrame = cf, + Color = BODY, + Material = BODY_MAT, + CustomPhysicalProperties = PhysicalProperties.new(1.2, 0.3, 0.2), + }) + model.PrimaryPart = chassis + + -- Декор: приварен к раме, без массы и столкновений. + local function deco(props, className: string?) + props.CanCollide = false + props.Massless = true + props.CFrame = cf * props.CFrame + local p = newPart(model, className or "Part", props) + weld(chassis, p) + return p + end + + -- Водительское место + 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, + 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) + props.Color = props.Color or ARMOR + props.Material = props.Material or Enum.Material.DiamondPlate + local p = deco(props) + p:SetAttribute("Armor", true) + return p + end + + -- Перед + 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 + deco({ Size = Vector3.new(0.35, 0.35, 1.6), CFrame = CFrame.new(x, 0.1, -6.3), Color = STEEL, Material = Enum.Material.Metal }) + end + elseif front == "ram" then + -- Наклонный отвал из листа железа на двух кронштейнах + deco({ Size = Vector3.new(7, 2.2, 0.4), CFrame = CFrame.new(0, 0.4, -5.9) * CFrame.Angles(math.rad(-25), 0, 0), Color = STEEL:Lerp(RUST, 0.5), Material = Enum.Material.DiamondPlate }) + for _, x in { -1.8, 1.8 } do + deco({ Size = Vector3.new(0.4, 0.4, 1.4), CFrame = CFrame.new(x, 0.2, -5.2), Color = DARK, Material = Enum.Material.Metal }) + end + for x = -3, 3, 1.5 do + deco({ Size = Vector3.new(0.6, 0.15, 0.15), CFrame = CFrame.new(x, -0.55, -6.45), Color = Color3.fromRGB(220, 180, 40), Material = Enum.Material.Metal }) + end + elseif front == "bucket" then + -- Ковш экскаватора: дно, задняя и боковые стенки, зубья, два рычага к раме + local yellow = Color3.fromRGB(205, 160, 40):Lerp(RUST, 0.25) + deco({ Size = Vector3.new(7, 0.3, 2.6), CFrame = CFrame.new(0, -0.55, -6.5) * CFrame.Angles(math.rad(-8), 0, 0), Color = yellow, Material = Enum.Material.Metal }) + deco({ Size = Vector3.new(7, 2.2, 0.3), CFrame = CFrame.new(0, 0.45, -5.3) * CFrame.Angles(math.rad(12), 0, 0), Color = yellow, Material = Enum.Material.Metal }) + for _, x in { -3.5, 3.5 } do + deco({ Size = Vector3.new(0.3, 1.6, 2.6), CFrame = CFrame.new(x, 0.15, -6.4), Color = yellow, Material = Enum.Material.Metal }) + end + for x = -3, 3, 1.5 do + deco({ Size = Vector3.new(0.45, 0.25, 0.9), CFrame = CFrame.new(x, -0.72, -8.1), Color = STEEL, Material = Enum.Material.Metal }) + end + for _, x in { -1.6, 1.6 } do + deco({ Size = Vector3.new(0.45, 0.45, 1.4), CFrame = CFrame.new(x, 0.6, -4.7), Color = DARK, Material = Enum.Material.Metal }) + end + elseif front == "bayonets" then + -- Поперечина и четыре штыка, крайние чуть разведены в стороны + deco({ Size = Vector3.new(6.4, 0.5, 0.5), CFrame = CFrame.new(0, 0.2, -5.3), Color = DARK, Material = Enum.Material.Metal }) + for _, x in { -2.6, -0.9, 0.9, 2.6 } do + local blade = CFrame.new(x, 0.2, -5.4) * CFrame.Angles(0, -x / 2.6 * 0.12, 0) + deco({ Size = Vector3.new(0.14, 0.45, 4), CFrame = blade * CFrame.new(0, 0, -2), Color = STEEL, Material = Enum.Material.Metal }) + 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 + + -- Зад (мотор — коробка 4×1.8×2.4 с центром в (0, 1.4, 3.9), выхлопные трубы по бокам) + 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 }) + end + for _, x in { -2.1, -0.7, 0.7, 2.1 } do + deco({ Size = Vector3.new(0.18, 0.18, 2.4), CFrame = CFrame.new(x, 2.9, 3.9), Color = FRAME, Material = FRAME_MAT }) + end + for _, x in { -2.1, 2.1 } do + for _, z in { 2.8, 5 } do + deco({ Size = Vector3.new(0.2, 1.2, 0.2), CFrame = CFrame.new(x, 2.3, z), Color = FRAME, Material = FRAME_MAT }) + end + end + elseif rear == "hood" then + armorPlate({ Size = Vector3.new(5.4, 0.3, 3.4), CFrame = CFrame.new(0, 3.05, 4.1) * CFrame.Angles(math.rad(-6), 0, 0) }) + for _, x in { -2.7, 2.7 } do + 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 }) + 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 }) + end + end + + -- Броня + 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 }) + 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 }) + 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) }) + 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 }) + 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 }) + 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 }) + 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 }) + 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 }) + local light = Instance.new("SpotLight") + light.Face = Enum.NormalId.Front + light.Range = 55 + light.Angle = 70 + light.Brightness = 3 + light.Color = Color3.fromRGB(255, 225, 170) + 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 }) + local turret = newPart(model, "Part", { + Name = "GunTurret", + Size = Vector3.new(0.6, 0.6, 0.6), + CFrame = cf * GunMath.Mount, + Transparency = 1, + CanCollide = false, + Massless = true, + }) + local gunMotor = Instance.new("Motor6D") + gunMotor.Name = "GunMotor" + gunMotor.Part0 = chassis + gunMotor.Part1 = turret + gunMotor.C0 = GunMath.Mount + gunMotor.Parent = chassis + + local function gunPart(props) + props.CanCollide = false + props.Massless = true + props.CFrame = cf * GunMath.Mount * props.CFrame + local p = newPart(model, "Part", props) + weld(turret, p) + return p + end + -- Ствол вдоль -Z турели: цилиндр длиной length с центром на z, срез у GunMath.Muzzle (z ≈ -4.6). + local function barrel(x: number, y: number, z: number, length: number, thickness: number, color: Color3?) + gunPart({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(length, thickness, thickness), CFrame = CFrame.new(x, y, z) * CFrame.Angles(0, math.pi / 2, 0), Color = color or STEEL, Material = Enum.Material.Metal }) + end + local OLIVE = Color3.fromRGB(75, 82, 50) + + -- Пушка из слота «Оружие» + if weapon == "mg_heavy" then + gunPart({ Size = Vector3.new(1.1, 0.9, 2.4), CFrame = CFrame.new(0, 0.2, -0.3), Color = DARK, Material = Enum.Material.Metal }) + barrel(0, 0.25, -2.95, 3.3, 0.36) + barrel(0, 0.25, -2.2, 1.6, 0.62, DARK) -- кожух охлаждения + barrel(0, 0.25, -4.4, 0.45, 0.52, DARK) -- дульный тормоз + gunPart({ Size = Vector3.new(0.85, 0.85, 1.3), CFrame = CFrame.new(0.95, 0.1, -0.2), Color = OLIVE, Material = Enum.Material.Metal }) + elseif weapon == "mg_twin" then + gunPart({ Size = Vector3.new(1.5, 0.8, 2.3), CFrame = CFrame.new(0, 0.2, -0.3), Color = DARK, Material = Enum.Material.Metal }) + for _, x in { -0.34, 0.34 } do + barrel(x, 0.25, -2.95, 3.2, 0.28) + barrel(x, 0.25, -1.6, 0.5, 0.5, DARK) + gunPart({ Size = Vector3.new(0.6, 0.6, 0.9), CFrame = CFrame.new(x * 3.4, 0.1, -0.2), Color = OLIVE, Material = Enum.Material.Metal }) + end + elseif weapon == "cannon" then + gunPart({ Size = Vector3.new(1.3, 1.1, 2.1), CFrame = CFrame.new(0, 0.3, 0), Color = DARK, Material = Enum.Material.Metal }) + barrel(0, 0.3, -2.8, 3.6, 0.6, STEEL:Lerp(DARK, 0.3)) + gunPart({ Size = Vector3.new(0.95, 0.55, 0.6), CFrame = CFrame.new(0, 0.3, -4.35), Color = DARK, Material = Enum.Material.Metal }) -- дульный тормоз + gunPart({ Size = Vector3.new(2.6, 1.6, 0.2), CFrame = CFrame.new(0, 0.35, -1.15), Color = DARK:Lerp(OLIVE, 0.4), Material = Enum.Material.DiamondPlate }) -- щиток + elseif weapon == "rockets" then + -- Блок из шести труб + gunPart({ Size = Vector3.new(1.9, 1.3, 2.6), CFrame = CFrame.new(0, 0.4, -3.2), Color = OLIVE, Material = Enum.Material.Metal }) + for _, x in { -0.55, 0, 0.55 } do + for _, y in { 0.1, 0.7 } do + barrel(x, y, -4.52, 0.1, 0.45, Color3.fromRGB(20, 20, 20)) + end + end + gunPart({ Size = Vector3.new(0.8, 0.7, 1.6), CFrame = CFrame.new(0, 0.1, -1.2), Color = DARK, Material = Enum.Material.Metal }) + else -- mg_light + gunPart({ Size = Vector3.new(0.8, 0.7, 2.1), CFrame = CFrame.new(0, 0.2, -0.3), Color = DARK, Material = Enum.Material.Metal }) + barrel(0, 0.25, -2.95, 3.2, 0.24) + barrel(0, 0.25, -1.6, 0.4, 0.45, DARK) + gunPart({ Size = Vector3.new(0.55, 0.5, 0.8), CFrame = CFrame.new(0.65, 0.1, -0.2), Color = OLIVE, Material = Enum.Material.Metal }) + end + gunPart({ Size = Vector3.new(0.9, 0.08, 0.5), CFrame = CFrame.new(0, 0.12, 0.9) * CFrame.Angles(math.rad(-20), 0, 0), Color = DARK, Material = Enum.Material.Metal }) + local flash = gunPart({ + Name = "MuzzleFlash", + Size = Vector3.new(0.8, 0.8, 0.5), + CFrame = GunMath.Muzzle, + Color = Color3.fromRGB(255, 200, 90), + Material = Enum.Material.Neon, + Transparency = 1, + }) + local flashLight = Instance.new("PointLight") + flashLight.Color = Color3.fromRGB(255, 170, 70) + flashLight.Range = 14 + flashLight.Brightness = 4 + 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 }) + local smoke = Instance.new("Smoke") + smoke.Color = Color3.fromRGB(60, 55, 50) + smoke.Opacity = 0.15 + smoke.RiseVelocity = 4 + 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 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") + slide.Attachment0 = attachment(chassis, CFrame.new(center) * VERTICAL, w.name .. "Slide") + slide.Attachment1 = attachment(hub, VERTICAL, "Slide") + slide.LimitsEnabled = true + slide.LowerLimit = -B.SuspensionTravel + slide.UpperLimit = B.SuspensionTravel * 0.7 + slide.Parent = hub + + local spring = Instance.new("SpringConstraint") + spring.Attachment0 = attachment(chassis, CFrame.new(center + Vector3.new(0, SPRING_TOP, 0)), w.name .. "SpringTop") + spring.Attachment1 = slide.Attachment1 + -- Свободная длина подобрана так, чтобы под весом багги пружина была чуть сжата. + spring.FreeLength = SPRING_TOP + 0.8 + spring.Stiffness = B.SpringStiffness + spring.Damping = B.SpringDamping + spring.Parent = hub + + local axleParent = hub + if w.steer then + local knuckle = newPart(model, "Part", { Name = w.name .. "Knuckle", Size = Vector3.new(1, 1, 1), CFrame = cf * CFrame.new(center), CanCollide = false, Transparency = 1 }) + local servo = Instance.new("HingeConstraint") + servo.Attachment0 = attachment(hub, VERTICAL, "Steer") + servo.Attachment1 = attachment(knuckle, VERTICAL, "Steer") + servo.ActuatorType = Enum.ActuatorType.Servo + servo.ServoMaxTorque = 100000 + servo.AngularSpeed = B.SteerSpeed + servo.LimitsEnabled = true + servo.LowerAngle = -B.SteerAngle - 5 + servo.UpperAngle = B.SteerAngle + 5 + servo.Parent = knuckle + table.insert(servos, servo) + axleParent = knuckle + end + + -- У цилиндра ось вдоль X — совпадает с осью колеса. + local wheel = newPart(model, "Part", { + Name = w.name .. "Wheel", + Shape = Enum.PartType.Cylinder, + Size = Vector3.new(WIDTH, R * 2, R * 2), + CFrame = cf * CFrame.new(center), + Color = TIRE, + 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), + }) + 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) + + -- При повороте руля и ходе подвески колесо заходит под раму — не даём им цепляться. + for _, body in { chassis, seat } do + local noCollide = Instance.new("NoCollisionConstraint") + noCollide.Part0 = wheel + noCollide.Part1 = body + noCollide.Parent = wheel + end + + local motor = Instance.new("HingeConstraint") + motor.Attachment0 = attachment(axleParent, CFrame.new(), "Axle") + motor.Attachment1 = attachment(wheel, CFrame.new(), "Axle") + motor.ActuatorType = Enum.ActuatorType.Motor + motor.MotorMaxTorque = B.CoastTorque + motor.Parent = wheel + table.insert(motors, motor) + end + + -- Витрина: всё остаётся закреплённым, сесть нельзя. + if options.display then + seat.Disabled = true + model.Parent = options.parent or workspace + return model + end + + local owner: Player? = options.owner + if owner then + model.Name = "Buggy_" .. owner.UserId + model:SetAttribute("OwnerId", owner.UserId) + end + + -- «Сесть» по клавише E — удобнее, чем запрыгивать на сиденье. + local prompt = Instance.new("ProximityPrompt") + prompt.ActionText = "Сесть за руль" + prompt.ObjectText = if owner then "Багги · " .. owner.DisplayName else "Багги" + prompt.KeyboardKeyCode = Enum.KeyCode.E + prompt.HoldDuration = 0 + prompt.MaxActivationDistance = 12 + prompt.RequiresLineOfSight = false + prompt.Parent = chassis + prompt.Triggered:Connect(function(player) + if owner and player ~= owner then + return + end + local character = player.Character + local humanoid = character and character:FindFirstChildOfClass("Humanoid") + if humanoid and humanoid.Health > 0 and not seat.Occupant and not humanoid.SeatPart then + seat:Sit(humanoid) + end + end) + + -- Физику считает водитель — так управление без задержек. + local driverHumanoid: Humanoid? = nil + seat:GetPropertyChangedSignal("Occupant"):Connect(function() + local occupant = seat.Occupant + local player = occupant and Players:GetPlayerFromCharacter(occupant.Parent) + + -- В бою (на карте команды, атрибут Arena от Lobby) из багги не выйти: выпрыгнул — сажаем обратно. + -- Уход с карты и смерть сюда не попадают: Lobby сначала сбрасывает Arena, у погибшего здоровье 0. + local left = driverHumanoid + driverHumanoid = if occupant and player == owner then occupant else nil + if not occupant and left and owner and (owner:GetAttribute("Arena") or 0) > 0 then + task.delay(0.1, function() + if model.Parent and left.Parent and left.Health > 0 and not left.SeatPart and not seat.Occupant + and (owner:GetAttribute("Arena") or 0) > 0 then + seat:Sit(left) + end + end) + end + -- В личную багги садится только хозяин (VehicleSeat сажает и при касании). + if owner and occupant and player ~= owner then + local seatWeld = seat:FindFirstChild("SeatWeld") + if seatWeld then + seatWeld:Destroy() + end + return + end + prompt.Enabled = occupant == nil + pcall(function() + if player then + chassis:SetNetworkOwner(player) + else + chassis:SetNetworkOwnershipAuto() + end + end) + end) + + model.Parent = options.parent or workspace + for _, d in model:GetDescendants() do + if d:IsA("BasePart") then + d.Anchored = false + end + end + + active[model] = { + seat = seat, + chassis = chassis, + motors = motors, + servos = servos, + wheelRadius = R, + speedFactor = Buggy.SpeedFactor(setup), + throttle = 0, + -- spec — параметры пушки из слота «Оружие» (Config.Garage.Parts → gun) + gun = { motor = gunMotor, spec = weaponItem.gun, heat = 0, heatTime = os.clock(), lastShot = 0, overheated = false }, + } + return model +end + +function Buggy.Get(model: Model) + return active[model] +end + +function Buggy.Driver(model: Model): Player? + local data = active[model] + local occupant = data and data.seat.Occupant + return occupant and Players:GetPlayerFromCharacter(occupant.Parent) +end + +function Buggy.FindDrivenBy(player: Player): Model? + for model in active do + if Buggy.Driver(model) == player then + return model + end + end + return nil +end + +-- Перевернуть на колёса и чуть приподнять. +function Buggy.Flip(model: Model) + local data = active[model] + if not data then + return + end + local chassis = data.chassis + local look = chassis.CFrame.LookVector * Vector3.new(1, 0, 1) + if look.Magnitude < 0.1 then + look = Vector3.new(0, 0, -1) + end + local position = 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 + d.AssemblyLinearVelocity = Vector3.zero + d.AssemblyAngularVelocity = Vector3.zero + end + end +end + +function Buggy.Destroy(model: Model) + active[model] = nil + model:Destroy() +end + +-- Плавно ведёт value к target: разгон за ThrottleRise секунд, сброс — за ThrottleFall. +local function approach(value: number, target: number, dt: number): number + local rising = math.abs(target) > math.abs(value) and (target >= 0) == (value >= 0) + local step = dt / (if rising then B.ThrottleRise else B.ThrottleFall) + if value < target then + return math.min(value + step, target) + end + return math.max(value - step, target) +end + +function Buggy.Start() + RunService.Heartbeat:Connect(function(dt) + for model, data in active do + if not model.Parent then + active[model] = nil + continue + end + local input = data.seat.ThrottleFloat + local steer = data.seat.SteerFloat + data.throttle = approach(data.throttle, input, dt) + + -- Целевая скорость колёс (studs/с). Только поворот без газа — медленно ползём вперёд. + -- Тяжёлые детали (броня, гусеницы) снижают максимальную скорость. + local maxSpeed = B.MaxSpeed * data.speedFactor + local speed + if input == 0 and steer ~= 0 and data.seat.Occupant then + -- Газ сбрасывается плавно, так что после отпускания W машина мягко замедляется до ползущего хода. + speed = math.max(data.throttle * maxSpeed, B.CreepSpeed) + elseif data.throttle >= 0 then + speed = data.throttle * maxSpeed + else + speed = data.throttle * B.ReverseSpeed * data.speedFactor + end + local driving = input ~= 0 or (steer ~= 0 and data.seat.Occupant ~= nil) + + -- Вперёд — это -Z рамы, поэтому колёса крутим в отрицательную сторону вокруг оси X. + local angular = -speed / data.wheelRadius * B.DriveSign + local torque = if driving then B.MotorTorque else B.CoastTorque + for _, motor in data.motors do + motor.AngularVelocity = angular + motor.MotorMaxTorque = torque + end + + -- Чем быстрее едем, тем меньше угол руля — чтобы на скорости машину не срывало в занос. + local currentSpeed = data.chassis.AssemblyLinearVelocity.Magnitude + local speedFactor = math.clamp(currentSpeed / maxSpeed, 0, 1) + local angle = B.SteerAngle * (1 - (1 - B.HighSpeedSteer) * speedFactor) + -- Положительный угол поворачивает колёса влево, а SteerFloat > 0 — это D (вправо). + for _, servo in data.servos do + servo.TargetAngle = -steer * angle * B.SteerSign + end + + -- Автопереворот: лежит на боку или на крыше AutoFlipTime секунд подряд — ставим на колёса. + -- Время переворота — в атрибуте FlipAt, по нему водитель видит обратный отсчёт. + local now = workspace:GetServerTimeNow() + if data.chassis.CFrame.UpVector.Y < B.AutoFlipTilt then + if not data.flipAt then + data.flipAt = now + B.AutoFlipTime + model:SetAttribute("FlipAt", data.flipAt) + elseif now >= data.flipAt then + Buggy.Flip(model) + end + elseif data.flipAt then + data.flipAt = nil + model:SetAttribute("FlipAt", nil) + end + end + end) +end + +return Buggy diff --git a/Zombi/src/server/Cases.luau b/Zombi/src/server/Cases.luau new file mode 100644 index 0000000..b668adc --- /dev/null +++ b/Zombi/src/server/Cases.luau @@ -0,0 +1,251 @@ +-- Кейсы: копятся у игрока (выпадают на колесе фортуны), открываются только ключом. +-- Ключ — developer product за Robux (Config.Cases.ProductId). Нет ключа — при открытии сразу предлагаем купить, +-- после покупки кейс открывается сам. Содержимое — Config.Cases.Loot, выдача — по kind через Cases.Rewards. +-- Каждое изменение сразу пишется в DataStore через UpdateAsync, покупки учитываются по PurchaseId — без дублей. + +local DataStoreService = game:GetService("DataStoreService") +local MarketplaceService = game:GetService("MarketplaceService") +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage.Shared.Config) + +local CC = Config.Cases +local Cases = {} + +-- Выдача содержимого кейса: Cases.Rewards[kind](player, item). Покраски регистрирует Fortune. +Cases.Rewards = {} :: { [string]: (Player, any) -> () } + +local KEEP_PURCHASES = 50 -- сколько последних PurchaseId помним для защиты от повторной выдачи + +local store: DataStore? = nil +pcall(function() + store = DataStoreService:GetDataStore("Cases_v1") +end) + +-- [userId] = { cases, keys, purchases, loaded, canSave, opening } +local states = {} +local wantOpen = {} -- [Player] = true — купил ключ из меню: после покупки открываем кейс сразу +local lastAction = {} -- [Player] = os.clock() +local rng = Random.new() +local Result: RemoteEvent + +-- Открывать можно, только когда задано содержимое и товар — иначе игрок заплатил бы за пустой кейс. +function Cases.Enabled(): boolean + return CC.ProductId ~= 0 and #CC.Loot > 0 +end + +local function normalize(data) + local d = { cases = 0, keys = 0, purchases = {} } + if typeof(data) == "table" then + if typeof(data.cases) == "number" then + d.cases = math.max(0, math.floor(data.cases)) + end + if typeof(data.keys) == "number" then + d.keys = math.max(0, math.floor(data.keys)) + end + if typeof(data.purchases) == "table" then + for _, id in data.purchases do + if typeof(id) == "string" then + table.insert(d.purchases, id) + end + end + end + end + return d +end + +local function publish(userId: number) + local player = Players:GetPlayerByUserId(userId) + local s = states[userId] + if player and s then + player:SetAttribute("Cases", s.cases) + player:SetAttribute("CaseKeys", s.keys) + end +end + +-- change(data) меняет данные и возвращает true, или false — отказ (ничего не записываем). +-- Возвращает, применилось ли изменение. Работает и для игрока не в сети (например, приз с колеса после выхода). +local function mutate(userId: number, change: (any) -> boolean): boolean + local s = states[userId] + -- Игрок только зашёл: ждём загрузку, иначе она затрёт изменение старыми данными. + local deadline = os.clock() + 15 + while s and not s.loaded and os.clock() < deadline do + task.wait(0.1) + end + if s and not s.loaded then + return false + end + if store and (not s or s.canSave) then + local applied = false + local ok, result = pcall(function() + return store:UpdateAsync("u" .. userId, function(old) + local d = normalize(old) + applied = change(d) + return if applied then d else nil + end) + end) + if not ok then + warn("Кейсы: не удалось записать", userId, result) + return false + end + if applied and states[userId] == s and s then + s.cases, s.keys, s.purchases = result.cases, result.keys, result.purchases + publish(userId) + end + return applied + end + -- DataStore недоступен (Studio без доступа к API) — только в памяти. + if s and change(s) then + publish(userId) + return true + end + return false +end + +function Cases.Give(userId: number, count: number): boolean + return mutate(userId, function(d) + d.cases += count + return true + end) +end + +local function roll() + local total = 0 + for _, item in CC.Loot do + total += item.weight or 1 + end + local pick = rng:NextNumber(0, total) + for _, item in CC.Loot do + pick -= item.weight or 1 + if pick <= 0 then + return item + end + end + return CC.Loot[#CC.Loot] +end + +local function open(player: Player) + local s = states[player.UserId] + if not Cases.Enabled() or not s or not s.loaded or s.opening or s.cases < 1 then + return + end + if s.keys < 1 then + wantOpen[player] = true + MarketplaceService:PromptProductPurchase(player, CC.ProductId) + return + end + s.opening = true + local ok = mutate(player.UserId, function(d) + if d.cases < 1 or d.keys < 1 then + return false + end + d.cases -= 1 + d.keys -= 1 + return true + end) + s.opening = false + if not ok then + return + end + local item = roll() + local give = Cases.Rewards[item.kind] + if give then + give(player, item) + else + warn("Кейсы: нет выдачи для kind =", item.kind) + end + Result:FireClient(player, item.name) +end + +local function processReceipt(receipt) + if receipt.ProductId ~= CC.ProductId then + return Enum.ProductPurchaseDecision.NotProcessedYet + end + local userId = receipt.PlayerId + local already = false + local applied = mutate(userId, function(d) + if table.find(d.purchases, receipt.PurchaseId) then + already = true -- эту покупку уже выдали + return false + end + d.keys += 1 + table.insert(d.purchases, receipt.PurchaseId) + while #d.purchases > KEEP_PURCHASES do + table.remove(d.purchases, 1) + end + return true + end) + if not applied and not already then + return Enum.ProductPurchaseDecision.NotProcessedYet -- Roblox повторит позже + end + local player = Players:GetPlayerByUserId(userId) + if player and wantOpen[player] then + wantOpen[player] = nil + task.spawn(open, player) + end + return Enum.ProductPurchaseDecision.PurchaseGranted +end + +local function onPlayerAdded(player: Player) + local userId = player.UserId + local s = { cases = 0, keys = 0, purchases = {}, loaded = false, canSave = false, opening = false } + states[userId] = s + publish(userId) + local ok, data = false, nil + if store then + ok, data = pcall(function() + return store:GetAsync("u" .. userId) + end) + end + if states[userId] ~= s then + return + end + if ok then + local d = normalize(data) + s.cases, s.keys, s.purchases = d.cases, d.keys, d.purchases + end + s.canSave = ok + s.loaded = true + publish(userId) +end + +function Cases.Init(remotes: Folder) + local Action = Instance.new("RemoteEvent") + Action.Name = "CaseAction" + Action.Parent = remotes + Result = Instance.new("RemoteEvent") + Result.Name = "CaseResult" + Result.Parent = remotes + + Action.OnServerEvent:Connect(function(player, action) + local now = os.clock() + if lastAction[player] and now - lastAction[player] < 0.5 then + return + end + lastAction[player] = now + if action == "open" then + open(player) + end + end) + + MarketplaceService.ProcessReceipt = processReceipt + MarketplaceService.PromptProductPurchaseFinished:Connect(function(userId, productId, purchased) + local player = Players:GetPlayerByUserId(userId) + if player and productId == CC.ProductId and not purchased then + wantOpen[player] = nil + end + end) + + Players.PlayerAdded:Connect(onPlayerAdded) + Players.PlayerRemoving:Connect(function(player) + states[player.UserId] = nil + wantOpen[player] = nil + lastAction[player] = nil + end) + for _, player in Players:GetPlayers() do + task.spawn(onPlayerAdded, player) + end +end + +return Cases diff --git a/Zombi/src/server/Fortune.luau b/Zombi/src/server/Fortune.luau new file mode 100644 index 0000000..000b766 --- /dev/null +++ b/Zombi/src/server/Fortune.luau @@ -0,0 +1,400 @@ +-- Колесо фортуны на пьедестале в ангаре. Крутить — раз в Config.Fortune.Cooldown на игрока (E у пьедестала). +-- Призы — редкие покраски багги (Config.Garage.Paints с rare = true, открытые сохраняются в DataStore) +-- и кейсы (см. Cases). Выпала покраска, которая уже есть, — попытка возвращается. +-- Шанс сектора пропорционален его весу (Config.Fortune.Weights), ширина на колесе — тоже. +-- Анимацию вращения рисуют клиенты (Fortune.client) по атрибутам модели; сервер в конце ставит колесо в итоговый угол. + +local DataStoreService = game:GetService("DataStoreService") +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage.Shared.Config) +local Cases = require(script.Parent.Cases) +local Hangar = require(script.Parent.Hangar) +local Shards = require(script.Parent.Shards) + +local FC = Config.Fortune +local Fortune = {} + +local RADIUS = 5 +local AXLE = 7.5 -- высота оси колеса над полом +local DARK = Color3.fromRGB(38, 36, 34) +local HAZARD = Color3.fromRGB(220, 175, 40) +local RED = Color3.fromRGB(200, 40, 30) +local EMPTY = Color3.fromRGB(70, 60, 52) +local CASE = Color3.fromRGB(120, 60, 170) +local SHARDS = Color3.fromRGB(50, 140, 165) + +local store: DataStore? = nil +pcall(function() + store = DataStoreService:GetDataStore("FortuneWheel_v1") +end) + +-- [Player] = { paints = { [paintIndex] = true }, lastSpin = os.time() | nil, canSave } +local states = {} +local rng = Random.new() + +local model: Model +local wheel: Model +local prompt: ProximityPrompt +local base: CFrame -- центр колеса при угле 0, LookVector — к игрокам +local angle = 0 +local spinning = false +local Result: RemoteEvent + +local function rarePaint(name: string): number? + for index, item in Config.Garage.Paints do + if item.name == name and item.rare then + return index + end + end + return nil +end + +-- Секторы: { name, weight, from, to — углы на колесе, paint — номер в Config.Garage.Paints, case — приз-кейс }. +-- Угол отсчитывается от верха по часовой: сектор наверху, когда колесо повёрнуто на угол внутри [from, to]. +local sectors = {} +local totalWeight = 0 +for _, name in FC.Sectors do + totalWeight += FC.Weights[name] or 1 +end +local cursor = 0 +for i, name in FC.Sectors do + local weight = FC.Weights[name] or 1 + local span = weight / totalWeight * math.pi * 2 + sectors[i] = { name = name, weight = weight, from = cursor, to = cursor + span, paint = rarePaint(name), case = name == "Кейс", shards = FC.Shards[name] } + cursor += span +end + +local function part(parent: Instance, props, className: string?): BasePart + local p = Instance.new(className or "Part") + p.Anchored = true + p.TopSurface = Enum.SurfaceType.Smooth + p.BottomSurface = Enum.SurfaceType.Smooth + for k, v in props do + p[k] = v + end + p.Parent = parent + return p +end + +-- Треугольник из двух клиньев (a, b, c — точки в мире). +local function triangle(parent: Instance, a: Vector3, b: Vector3, c: Vector3, thickness: number, props) + local ab, ac, bc = b - a, c - a, c - b + local abd, acd, bcd = ab:Dot(ab), ac:Dot(ac), bc:Dot(bc) + if abd > acd and abd > bcd then + c, a = a, c + elseif acd > bcd and acd > abd then + a, b = b, a + end + ab, ac, bc = b - a, c - a, c - b + local right = ac:Cross(ab).Unit + local up = bc:Cross(right).Unit + local back = bc.Unit + local height = math.abs(ab:Dot(up)) + for _, half in { { (a + b) / 2, right, back, ab }, { (a + c) / 2, -right, -back, ac } } do + local p = table.clone(props) + p.Size = Vector3.new(thickness, height, math.abs(half[4]:Dot(back))) + p.CFrame = CFrame.fromMatrix(half[1], half[2], up, half[3]) + part(parent, p, "WedgePart") + end +end + +local function sign(parent: BasePart, face: Enum.NormalId, text: string, color: Color3) + local gui = Instance.new("SurfaceGui") + gui.Face = face + gui.SizingMode = Enum.SurfaceGuiSizingMode.PixelsPerStud + gui.PixelsPerStud = 40 + gui.LightInfluence = 0.2 + gui.Parent = parent + local label = Instance.new("TextLabel") + label.Size = UDim2.fromScale(1, 1) + label.BackgroundTransparency = 1 + label.Font = Enum.Font.GothamBlack + label.TextScaled = true + label.TextColor3 = color + label.TextStrokeTransparency = 0.5 + label.Text = text + label.Parent = gui + return label +end + +-- ===== Пьедестал и колесо ===== + +local function build() + local floor = Hangar.FortuneSpot + model = Instance.new("Model") + model.Name = "FortuneWheel" + base = CFrame.new(floor + Vector3.new(0, AXLE, 0)) -- смотрит на -Z, к центру ангара + + -- Ступенчатый пьедестал и стойка за колесом + part(model, { Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.6, 9, 9), CFrame = CFrame.new(floor + Vector3.new(0, 0.3, 0)) * CFrame.Angles(0, 0, math.pi / 2), Color = DARK, Material = Enum.Material.DiamondPlate }) + local step = part(model, { Name = "Pedestal", Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.6, 7, 7), CFrame = CFrame.new(floor + Vector3.new(0, 0.9, 0)) * CFrame.Angles(0, 0, math.pi / 2), Color = HAZARD, Material = Enum.Material.Metal }) + part(model, { Size = Vector3.new(1.6, AXLE - 1.2, 1.6), CFrame = CFrame.new(floor + Vector3.new(0, 1.2 + (AXLE - 1.2) / 2, 1.4)), Color = DARK, Material = Enum.Material.Metal }) + part(model, { Shape = Enum.PartType.Cylinder, Size = Vector3.new(2.2, 1, 1), CFrame = base * CFrame.new(0, 0, 0.7) * CFrame.Angles(0, math.pi / 2, 0), Color = DARK, Material = Enum.Material.Metal }) + + -- Указатель сверху: красный ромб, нижний угол показывает на выигрыш. + part(model, { Size = Vector3.new(1.3, 1.3, 0.5), CFrame = base * CFrame.new(0, RADIUS + 0.7, -0.5) * CFrame.Angles(0, 0, math.pi / 4), Color = RED, Material = Enum.Material.Neon, CanCollide = false }) + local plate = part(model, { Size = Vector3.new(12, 1.8, 0.3), CFrame = base * CFrame.new(0, RADIUS + 2.6, 0), Color = DARK, Material = Enum.Material.Metal, CanCollide = false }) + sign(plate, Enum.NormalId.Front, "КОЛЕСО ФОРТУНЫ", HAZARD) + local result = part(model, { Name = "ResultSign", Size = Vector3.new(14, 1.2, 0.2), CFrame = base * CFrame.new(0, RADIUS + 4.2, 0), Transparency = 1, CanCollide = false }) + sign(result, Enum.NormalId.Front, "раз в сутки · редкие покраски", Color3.fromRGB(235, 220, 200)).Name = "Text" + + -- Колесо: всё внутри вращается вместе с Hub. + wheel = Instance.new("Model") + wheel.Name = "Wheel" + local hub = part(wheel, { Name = "Hub", Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.8, 1.6, 1.6), CFrame = base * CFrame.new(0, 0, -0.45) * CFrame.Angles(0, math.pi / 2, 0), Color = HAZARD, Material = Enum.Material.Metal, CanCollide = false }) + hub.PivotOffset = hub.CFrame:ToObjectSpace(base) -- точка вращения — центр колеса с ориентацией base + wheel.PrimaryPart = hub + part(wheel, { Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.3, RADIUS * 2 + 0.8, RADIUS * 2 + 0.8), CFrame = base * CFrame.new(0, 0, 0.1) * CFrame.Angles(0, math.pi / 2, 0), Color = DARK, Material = Enum.Material.Metal, CanCollide = false }) + + for _, sector in sectors do + local from, to = sector.from, sector.to + local function rim(a: number): Vector3 + return (base * CFrame.new(math.sin(a) * RADIUS, math.cos(a) * RADIUS, -0.15)).Position + end + -- Чуть приглушаем цвета: светлые сектора (хром, лёд) иначе выгорают в белое. + local color = if sector.paint then Config.Garage.Paints[sector.paint].color:Lerp(DARK, 0.25) + elseif sector.case then CASE + elseif sector.shards then SHARDS + else EMPTY + -- Широкий сектор собираем из нескольких треугольников, чтобы край оставался круглым. + local pieces = math.ceil((to - from) / (math.pi / 4)) + for k = 0, pieces - 1 do + local a0 = from + (to - from) * k / pieces + local a1 = from + (to - from) * (k + 1) / pieces + triangle(wheel, (base * CFrame.new(0, 0, -0.15)).Position, rim(a0), rim(a1), 0.2, { Color = color, Material = Enum.Material.SmoothPlastic, CanCollide = false }) + end + -- Перемычка между секторами + local edge = CFrame.fromMatrix((base * CFrame.new(math.sin(from) * RADIUS / 2, math.cos(from) * RADIUS / 2, -0.3)).Position, base:VectorToWorldSpace(Vector3.new(math.cos(from), -math.sin(from), 0)), base:VectorToWorldSpace(Vector3.new(math.sin(from), math.cos(from), 0))) + part(wheel, { Size = Vector3.new(0.15, RADIUS, 0.1), CFrame = edge, Color = HAZARD, Material = Enum.Material.Metal, CanCollide = false }) + + -- Подпись вдоль радиуса, читается от центра к краю. + local mid = (from + to) / 2 + local out = base:VectorToWorldSpace(Vector3.new(math.sin(mid), math.cos(mid), 0)) + local side = base:VectorToWorldSpace(Vector3.new(math.cos(mid), -math.sin(mid), 0)) + local at = (base * CFrame.new(math.sin(mid) * RADIUS * 0.58, math.cos(mid) * RADIUS * 0.58, -0.3)).Position + local label = part(wheel, { Size = Vector3.new(3.4, 0.9, 0.05), CFrame = CFrame.fromMatrix(at, -out, side), Transparency = 1, CanCollide = false }) + local textColor = if color.R + color.G + color.B > 1.5 then DARK else Color3.fromRGB(240, 230, 215) + sign(label, Enum.NormalId.Front, string.upper(sector.name), textColor).TextStrokeTransparency = 1 + end + + -- Лампочки по ободу + for i = 0, 15 do + local a = i / 16 * math.pi * 2 + local bulb = part(wheel, { Shape = Enum.PartType.Ball, Size = Vector3.new(0.4, 0.4, 0.4), CFrame = base * CFrame.new(math.sin(a) * (RADIUS + 0.15), math.cos(a) * (RADIUS + 0.15), -0.3), Color = Color3.fromRGB(230, 180, 110), Material = Enum.Material.Neon, CanCollide = false }) + if i % 4 == 0 then + local light = Instance.new("PointLight") + light.Color = Color3.fromRGB(255, 200, 130) + light.Range = 8 + light.Brightness = 0.4 + light.Parent = bulb + end + end + wheel.Parent = model + + prompt = Instance.new("ProximityPrompt") + prompt.Name = "FortunePrompt" -- клиент подставляет свой таймер в ActionText (Fortune.client) + prompt.ActionText = "Крутить колесо" + prompt.ObjectText = "Колесо фортуны" + prompt.KeyboardKeyCode = Enum.KeyCode.E + prompt.HoldDuration = 0.3 + prompt.MaxActivationDistance = 10 + prompt.RequiresLineOfSight = false + prompt.Parent = step + + model:SetAttribute("Base", base) + model:SetAttribute("Angle", 0) + model.Parent = workspace +end + +-- ===== Данные игрока ===== + +local function publish(player: Player, state) + local owned = {} + for index in state.paints do + table.insert(owned, index) + end + table.sort(owned) + -- Через запятые и с запятыми по краям: клиент ищет ",номер,". + player:SetAttribute("RarePaints", "," .. table.concat(owned, ",") .. ",") + player:SetAttribute("NextSpin", if state.lastSpin then state.lastSpin + FC.Cooldown else 0) +end + +local function save(userId: number, state) + if not store or not state.canSave then + return + end + local owned = {} + for index in state.paints do + table.insert(owned, index) + end + local ok, err = pcall(function() + store:SetAsync("u" .. userId, { paints = owned, lastSpin = state.lastSpin }) + end) + if not ok then + warn("Не удалось сохранить колесо фортуны", userId, err) + end +end + +local function onPlayerAdded(player: Player) + -- Пока данные не загрузились, крутить нельзя (loaded = false). + local state = { paints = {}, lastSpin = nil, canSave = false, loaded = false } + states[player] = state + publish(player, state) + local ok, data = false, nil + if store then + ok, data = pcall(function() + return store:GetAsync("u" .. player.UserId) + end) + end + if states[player] ~= state then + return + end + if ok and typeof(data) == "table" then + for _, index in data.paints or {} do + local item = typeof(index) == "number" and Config.Garage.Paints[index] + if item and item.rare then + state.paints[index] = true + end + end + if typeof(data.lastSpin) == "number" then + state.lastSpin = data.lastSpin + end + end + -- Если DataStore недоступен (например, Studio без доступа к API), играем без сохранения, + -- чтобы не затереть настоящие данные пустыми. + state.canSave = ok + state.loaded = true + publish(player, state) +end + +function Fortune.HasPaint(player: Player, index: number): boolean + local item = Config.Garage.Paints[index] + if not item or not item.rare then + return true + end + local state = states[player] + return state ~= nil and state.paints[index] == true +end + +-- ===== Вращение ===== + +local function finish(player: Player, state, sector) + local text + if sector.case then + if Cases.Give(player.UserId, 1) then + text = "Кейс! Он в меню «Кейсы» слева сверху." + else + state.lastSpin = nil -- не получилось записать — возвращаем попытку + text = "Не удалось выдать кейс — крути ещё раз!" + end + elseif sector.shards then + if Shards.Add(player.UserId, sector.shards) then + text = ("+%d осколков! Трать их в гараже."):format(sector.shards) + else + state.lastSpin = nil + text = "Не удалось начислить осколки — крути ещё раз!" + end + elseif not sector.paint then + text = "Пусто. Повезёт в следующий раз!" + elseif state.paints[sector.paint] then + state.lastSpin = nil -- такая уже есть — попытка возвращается + text = ("«%s» уже есть — крути ещё раз!"):format(sector.name) + else + state.paints[sector.paint] = true + text = ("Новая покраска: «%s»! Выбери её в гараже."):format(sector.name) + end + if player.Parent then + publish(player, state) + Result:FireClient(player, text) + end + local sign = model:FindFirstChild("ResultSign") + local label = sign and sign:FindFirstChild("Text", true) :: TextLabel? + if label then + label.Text = ("%s · %s"):format(player.DisplayName, string.lower(sector.name)) + end + task.spawn(save, player.UserId, state) +end + +local function spin(player: Player) + local state = states[player] + if spinning or not state or not state.loaded then + return + end + local now = os.time() + if state.lastSpin and now - state.lastSpin < FC.Cooldown then + return + end + state.lastSpin = now + publish(player, state) + + local pick = rng:NextNumber(0, totalWeight) + local index = #sectors + for i, sector in sectors do + pick -= sector.weight + if pick <= 0 then + index = i + break + end + end + -- Итоговый угол: точка внутри сектора (не у самой границы) наверху, плюс 5–6 полных оборотов. + local sector = sectors[index] + local span = sector.to - sector.from + local target = rng:NextNumber(sector.from + span * 0.1, sector.to - span * 0.1) + local turns = math.ceil((angle + 5 * math.pi * 2 - target) / (math.pi * 2)) + target += turns * math.pi * 2 + + spinning = true + prompt.Enabled = false + model:SetAttribute("SpinFrom", angle) + model:SetAttribute("SpinTo", target) + model:SetAttribute("SpinStart", workspace:GetServerTimeNow()) + model:SetAttribute("Spinner", player.DisplayName) + + task.delay(FC.SpinTime, function() + angle = target % (math.pi * 2) + wheel:PivotTo(base * CFrame.Angles(0, 0, angle)) + model:SetAttribute("Angle", angle) + spinning = false + prompt.Enabled = true + finish(player, state, sectors[index]) + end) +end + +-- Открыть редкую покраску (куплена за осколки или выпала из кейса). Уже есть — ничего не меняется. +function Fortune.GivePaint(player: Player, index: number) + local state = states[player] + local item = Config.Garage.Paints[index] + if state and item and item.rare and not state.paints[index] then + state.paints[index] = true + publish(player, state) + task.spawn(save, player.UserId, state) + end +end + +-- Покраска из кейса: { kind = "paint", paint = "Золото" } +Cases.Rewards.paint = function(player: Player, item) + local index = rarePaint(item.paint or "") + if index then + Fortune.GivePaint(player, index) + end +end + +function Fortune.Init(remotes: Folder) + build() + Result = Instance.new("RemoteEvent") + Result.Name = "FortuneResult" + Result.Parent = remotes + + prompt.Triggered:Connect(spin) + Players.PlayerAdded:Connect(onPlayerAdded) + Players.PlayerRemoving:Connect(function(player) + states[player] = nil + end) + for _, player in Players:GetPlayers() do + task.spawn(onPlayerAdded, player) + end +end + +return Fortune diff --git a/Zombi/src/server/Garage.luau b/Zombi/src/server/Garage.luau new file mode 100644 index 0000000..3e47d4b --- /dev/null +++ b/Zombi/src/server/Garage.luau @@ -0,0 +1,590 @@ +-- Личный гараж: у каждого игрока своя комната далеко за картой с его багги на подъёмнике. +-- Апгрейд: детали из инвентаря ставятся в слоты (перед, колёса, зад, броня), отдельно — покраска. +-- Установка и инвентарь сохраняются в DataStore. +-- Выезда отсюда нет: багги с этим тюнингом появляется на карте команды, когда стартует лобби (см. Lobby). + +local DataStoreService = game:GetService("DataStoreService") +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage.Shared.Config) +local Buggy = require(script.Parent.Buggy) +local Cases = require(script.Parent.Cases) +local Fortune = require(script.Parent.Fortune) +local Shards = require(script.Parent.Shards) +local Hangar = require(script.Parent.Hangar) +local Loading = require(script.Parent.Loading) + +local Garage = {} + +local ORIGIN = CFrame.new(0, 400, 4000) -- гаражи стоят в ряд далеко за краем карты +local SPACING = 120 +-- Комната с запасом под облёт камеры в меню (радиус 17 + сдвиг кадра + отступ от стен, см. Garage.client): +-- багги стоит на 4 studs ближе к задней стене, до неё остаётся 22. +local ROOM_X, ROOM_Z, ROOM_H = 44, 52, 16 + +local WALL = Color3.fromRGB(88, 84, 78) +local DARK = Color3.fromRGB(38, 36, 34) +local HAZARD = Color3.fromRGB(220, 175, 40) +local RED = Color3.fromRGB(170, 40, 30) + +-- Покраски: ключ настройки → список вариантов и атрибут игрока, по которому клиент рисует выбор. +local COLORS = { + paint = { list = Config.Garage.Paints, attribute = "BuggyPaint" }, + accent = { list = Config.Garage.Accents, attribute = "BuggyAccent" }, +} +-- Слот детали → атрибут игрока с id установленной детали ("" — пусто): BuggyFront, BuggyWheels… +local function slotAttribute(slot: string): string + return "Buggy" .. string.upper(string.sub(slot, 1, 1)) .. string.sub(slot, 2) +end +local SLOTS = {} +for _, slot in Config.Garage.Slots do + SLOTS[slot.id] = slot +end + +-- Старые сохранения: колёса и бампер хранились номерами. +local OLD_WHEELS = { "wheels_std", "wheels_big", "wheels_low" } +local OLD_BUMPERS = { "spikes", "ram", "" } + +local store: DataStore? = nil +pcall(function() + store = DataStoreService:GetDataStore("BuggySetup_v1") +end) + +local folder: Folder +-- [Player] = { slot, room, display, setup, parts, door, buggy, dirty, lastChange } +-- parts — детали сверх стартовых: [id] = true +local states = {} +local usedSlots = {} + +local function part(parent: Instance, props, className: string?): BasePart + local p = Instance.new(className or "Part") + p.Anchored = true + p.TopSurface = Enum.SurfaceType.Smooth + p.BottomSurface = Enum.SurfaceType.Smooth + for k, v in props do + p[k] = v + end + p.Parent = parent + return p +end + +-- ===== Комната ===== + +local function buildRoom(player: Player, origin: CFrame): Model + local room = Instance.new("Model") + room.Name = tostring(player.UserId) + local function p(props, className: string?) + props.CFrame = origin * props.CFrame + return part(room, props, className) + end + + -- Пол, стены, потолок — коробка без щелей, чтобы не выпасть. + p({ Size = Vector3.new(ROOM_X, 1, ROOM_Z), CFrame = CFrame.new(0, -0.5, 0), Color = Color3.fromRGB(110, 106, 100), Material = Enum.Material.Concrete }) + p({ Size = Vector3.new(ROOM_X, 1, ROOM_Z), CFrame = CFrame.new(0, ROOM_H + 0.5, 0), Color = DARK, Material = Enum.Material.Metal }) + for _, side in { -1, 1 } do + p({ Size = Vector3.new(1, ROOM_H, ROOM_Z), CFrame = CFrame.new(side * (ROOM_X / 2 + 0.5), ROOM_H / 2, 0), Color = WALL, Material = Enum.Material.Brick }) + p({ Size = Vector3.new(ROOM_X + 2, ROOM_H, 1), CFrame = CFrame.new(0, ROOM_H / 2, side * (ROOM_Z / 2 + 0.5)), Color = WALL, Material = Enum.Material.Brick }) + end + -- Жёлтая полоса по низу стен + for _, side in { -1, 1 } do + p({ Size = Vector3.new(0.2, 1.2, ROOM_Z), CFrame = CFrame.new(side * ROOM_X / 2, 0.6, 0), Color = HAZARD, Material = Enum.Material.SmoothPlastic, CanCollide = false }) + p({ Size = Vector3.new(ROOM_X, 1.2, 0.2), CFrame = CFrame.new(0, 0.6, -ROOM_Z / 2), Color = HAZARD, Material = Enum.Material.SmoothPlastic, CanCollide = false }) + end + + -- Подъёмник под багги + p({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.3, 19, 19), CFrame = CFrame.new(0, 0.15, -4) * CFrame.Angles(0, 0, math.pi / 2), Color = HAZARD, Material = Enum.Material.SmoothPlastic }) + p({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.4, 17.5, 17.5), CFrame = CFrame.new(0, 0.2, -4) * CFrame.Angles(0, 0, math.pi / 2), Color = DARK, Material = Enum.Material.DiamondPlate }) + + -- Свет: четыре лампы-полосы + for _, z in { -18, -6, 6, 18 } do + local lamp = p({ Size = Vector3.new(14, 0.3, 1), CFrame = CFrame.new(0, ROOM_H - 0.2, z), Color = Color3.fromRGB(255, 235, 200), Material = Enum.Material.Neon, CanCollide = false }) + local light = Instance.new("PointLight") + light.Color = Color3.fromRGB(255, 230, 190) + light.Range = 30 + light.Brightness = 0.9 + light.Shadows = true + light.Parent = lamp + end + + -- Верстак с инструментами — у него открывается тюнинг. + local bench = p({ Size = Vector3.new(3, 0.4, 10), CFrame = CFrame.new(-ROOM_X / 2 + 2, 3.2, -6), Color = Color3.fromRGB(90, 66, 44), Material = Enum.Material.WoodPlanks }) + for _, z in { -10.5, -1.5 } do + p({ Size = Vector3.new(2.6, 3, 0.4), CFrame = CFrame.new(-ROOM_X / 2 + 2, 1.5, z), Color = DARK, Material = Enum.Material.Metal }) + end + p({ Size = Vector3.new(1.2, 1, 2), CFrame = CFrame.new(-ROOM_X / 2 + 2, 3.9, -9), Color = RED, Material = Enum.Material.Metal }) + p({ Size = Vector3.new(1.4, 1.8, 1.4), CFrame = CFrame.new(-ROOM_X / 2 + 2.2, 4.3, -3), Color = DARK, Material = Enum.Material.Metal }) + -- Перфопанель с ключами над верстаком + p({ Size = Vector3.new(0.2, 5, 10), CFrame = CFrame.new(-ROOM_X / 2 + 0.1, 7, -6), Color = Color3.fromRGB(150, 120, 80), Material = Enum.Material.Wood }) + for i = 0, 5 do + p({ Size = Vector3.new(0.2, 2 + (i % 3) * 0.4, 0.3), CFrame = CFrame.new(-ROOM_X / 2 + 0.3, 7, -10 + i * 1.6) * CFrame.Angles(math.rad(10 * (i % 2 * 2 - 1)), 0, 0), Color = Color3.fromRGB(170, 170, 175), Material = Enum.Material.Metal, CanCollide = false }) + end + local prompt = Instance.new("ProximityPrompt") + prompt.Name = "TuningPrompt" -- клиент открывает меню тюнинга (Garage.client) + prompt.ActionText = "Тюнинг багги" + prompt.ObjectText = "Верстак" + prompt.KeyboardKeyCode = Enum.KeyCode.E + prompt.HoldDuration = 0 + prompt.MaxActivationDistance = 10 + prompt.RequiresLineOfSight = false + prompt.Parent = bench + + -- Стеллаж и колёса в углу + for y = 1, 3 do + p({ Size = Vector3.new(3, 0.3, 12), CFrame = CFrame.new(ROOM_X / 2 - 2, y * 3, -8), Color = DARK, Material = Enum.Material.Metal }) + end + for _, z in { -13.8, -2.2 } do + p({ Size = Vector3.new(3, 10, 0.3), CFrame = CFrame.new(ROOM_X / 2 - 2, 5, z), Color = DARK, Material = Enum.Material.Metal }) + end + for i = 0, 3 do + p({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(1.3, 3.4, 3.4), CFrame = CFrame.new(ROOM_X / 2 - 3, 0.65 + i * 1.3, ROOM_Z / 2 - 3) * CFrame.Angles(0, 0, math.pi / 2), Color = Color3.fromRGB(24, 24, 24), Material = Enum.Material.Fabric }) + end + for i, color in { RED, Color3.fromRGB(60, 90, 140) } do + p({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(3, 2.2, 2.2), CFrame = CFrame.new(-ROOM_X / 2 + 2, 1.5, ROOM_Z / 2 - 2 - i * 2.4) * CFrame.Angles(0, 0, math.pi / 2), Color = color, Material = Enum.Material.Metal }) + end + + -- Табличка с именем хозяина на задней стене + local plate = p({ Size = Vector3.new(16, 2.4, 0.2), CFrame = CFrame.new(0, ROOM_H - 3, -ROOM_Z / 2 + 0.1), Color = DARK, Material = Enum.Material.Metal, CanCollide = false }) + local gui = Instance.new("SurfaceGui") + gui.Face = Enum.NormalId.Back -- смотрит внутрь комнаты (на +Z) + gui.SizingMode = Enum.SurfaceGuiSizingMode.PixelsPerStud + gui.PixelsPerStud = 40 + gui.LightInfluence = 0.3 + gui.Parent = plate + local label = Instance.new("TextLabel") + label.Size = UDim2.fromScale(1, 1) + label.BackgroundTransparency = 1 + label.Font = Enum.Font.GothamBlack + label.TextScaled = true + label.TextColor3 = HAZARD + label.Text = "ГАРАЖ · " .. string.upper(player.DisplayName) + label.Parent = gui + + -- Ворота назад в ангар + local door = p({ Name = "ExitDoor", Size = Vector3.new(12, 10, 0.4), CFrame = CFrame.new(0, 5, ROOM_Z / 2 - 0.2), Color = Color3.fromRGB(118, 122, 112), Material = Enum.Material.CorrodedMetal }) + for y = 1, 9 do + p({ Size = Vector3.new(12, 0.12, 0.6), CFrame = CFrame.new(0, y, ROOM_Z / 2 - 0.2), Color = DARK, Material = Enum.Material.Metal, CanCollide = false }) + end + local exit = Instance.new("ProximityPrompt") + exit.Name = "ExitPrompt" + exit.ActionText = "Выйти в ангар" + exit.ObjectText = "Ворота" + exit.KeyboardKeyCode = Enum.KeyCode.E + exit.HoldDuration = 0.3 + exit.MaxActivationDistance = 10 + exit.RequiresLineOfSight = false + exit.Parent = door + exit.Triggered:Connect(function(who) + if who == player then + Garage.Leave(player) + end + end) + + room.Parent = folder + return room +end + +local function refreshDisplay(state) + if state.display then + state.display:Destroy() + end + -- Багги на подъёмнике мордой к воротам (к игроку). + local ground = state.origin * CFrame.new(0, 0.1, -4) * CFrame.Angles(0, math.pi, 0) + state.display = Buggy.Build(ground, { display = true, setup = state.setup, parent = state.room }) +end + +local function owns(state, id: string): boolean + local item = Config.PartById[id] + return item ~= nil and (item.starter == true or state.parts[id] == true) +end + +local function publishSetup(player: Player, state) + local setup = state.setup + for key, option in COLORS do + player:SetAttribute(option.attribute, setup[key]) + end + for id in SLOTS do + player:SetAttribute(slotAttribute(id), setup[id] or "") + end + -- Все детали игрока (вместе с установленными) через запятые: клиент ищет ",id,". + local owned = {} + for _, item in Config.Garage.Parts do + if owns(state, item.id) then + table.insert(owned, item.id) + end + end + player:SetAttribute("OwnedParts", "," .. table.concat(owned, ",") .. ",") +end + +-- Сохранение: { setup = {...}, parts = { id, ... } }. Раньше хранилась только настройка с номерами колёс и бампера. +local function loadSaved(state, data) + if typeof(data) ~= "table" then + return + end + local saved = if typeof(data.setup) == "table" then data.setup else data + for _, id in (if typeof(data.parts) == "table" then data.parts else {}) do + if typeof(id) == "string" and Config.PartById[id] then + state.parts[id] = true + end + end + if typeof(saved.wheels) == "number" then + saved.wheels = OLD_WHEELS[saved.wheels] + end + if typeof(saved.bumper) == "number" and saved.front == nil then + saved.front = OLD_BUMPERS[saved.bumper] + end + + local setup = Buggy.DefaultSetup() + for key, option in COLORS do + local value = saved[key] + if typeof(value) == "number" and option.list[value] then + setup[key] = value + end + end + for id, slot in SLOTS do + local value = saved[id] + if value == "" and not slot.required then + setup[id] = "" + elseif typeof(value) == "string" and owns(state, value) and Config.PartById[value].slot == id then + setup[id] = value + end + end + state.setup = setup +end + +local function save(player: Player, state) + if not store or not state.dirty or not state.canSave then + return + end + state.dirty = false + local parts = {} + for id in state.parts do + table.insert(parts, id) + end + local ok, err = pcall(function() + store:SetAsync("u" .. player.UserId, { setup = state.setup, parts = parts }) + end) + if not ok then + warn("Не удалось сохранить тюнинг", player.Name, err) + end +end + +-- ===== Перемещения ===== + +local function unseat(humanoid: Humanoid) + local seat = humanoid.SeatPart + local seatWeld = seat and seat:FindFirstChild("SeatWeld") + if seatWeld then + seatWeld:Destroy() + end + humanoid.Sit = false +end + +-- loadingText — переход в другую зону: экран загрузки, и персонаж стоит на месте, пока клиент +-- не подгрузит сцену (см. Loading). Без него — просто переносим (например, вернуть в круг лобби). +local function teleport(player: Player, cf: CFrame, loadingText: string?): boolean + local character = player.Character + local humanoid = character and character:FindFirstChildOfClass("Humanoid") + if not humanoid or humanoid.Health <= 0 then + return false + end + local token = if loadingText then Loading.Begin(player, loadingText) else nil + if player.Character ~= character or humanoid.Health <= 0 then + return false + end + unseat(humanoid) + pcall(function() + player:RequestStreamAroundAsync(cf.Position, 5) + end) + character:PivotTo(cf) + if token then + local root = character:FindFirstChild("HumanoidRootPart") :: BasePart? + if root then + root.Anchored = true + end + Loading.Finish(player, token, cf.Position) + if root then + root.Anchored = false + end + end + return true +end + +local function ensureRoom(player: Player, state) + if state.room then + return + end + local slot = 1 + while usedSlots[slot] do + slot += 1 + end + usedSlots[slot] = true + state.slot = slot + state.origin = ORIGIN * CFrame.new((slot - 1) * SPACING, 0, 0) + state.room = buildRoom(player, state.origin) + refreshDisplay(state) +end + +function Garage.Enter(player: Player, doorIndex: number) + local state = states[player] + if not state then + return + end + ensureRoom(player, state) + state.door = doorIndex + -- Встаём у ворот лицом к багги. + local spot = state.origin * CFrame.new(0, 3.5, ROOM_Z / 2 - 6) + if teleport(player, spot, "Гараж") then + player:SetAttribute("InGarage", true) + end +end + +function Garage.Leave(player: Player) + local state = states[player] + local door = Hangar.Doors[state and state.door or 1] or Hangar.Doors[1] + if state and teleport(player, door.frame * CFrame.new(0, 3.5, -7), "Ангар") then + player:SetAttribute("InGarage", false) + end +end + +Garage.Teleport = teleport + +function Garage.RemoveBuggy(player: Player) + local state = states[player] + if state and state.buggy then + Buggy.Destroy(state.buggy) + state.buggy = nil + end +end + +-- Ставит личную багги игрока в точку ground (смотрит по -Z) и сажает его за руль. +-- loadingText — подпись на экране загрузки, пока подгружается место. +function Garage.SpawnBuggy(player: Player, ground: CFrame, loadingText: string) + local state = states[player] + local character = player.Character + local humanoid = character and character:FindFirstChildOfClass("Humanoid") + if not state or not humanoid or humanoid.Health <= 0 then + return + end + if state.buggy then + Buggy.Destroy(state.buggy) + end + state.buggy = Buggy.Build(ground, { setup = state.setup, owner = player }) + local seat = state.buggy:FindFirstChild("DriverSeat") :: VehicleSeat + if not teleport(player, seat.CFrame * CFrame.new(0, 3, 0), loadingText) then + return + end + player:SetAttribute("InGarage", false) + -- Сажаем, только когда клиент уже перенёс персонажа к багги. Если посадить в тот же кадр, + -- клиент ещё стоит в гараже: сервер считает игрока водителем, а управление на клиенте не включается. + local buggy = state.buggy + local root = character:FindFirstChild("HumanoidRootPart") :: BasePart? + task.spawn(function() + for _ = 1, 20 do + task.wait(0.1) + if not root or (root.Position - seat.Position).Magnitude < 12 then + break + end + end + task.wait(0.3) -- на сервере позиция меняется сразу, даём клиенту время её получить + if state.buggy == buggy and buggy.Parent and humanoid.Health > 0 and not humanoid.SeatPart and not seat.Occupant then + seat:Sit(humanoid) + end + end) +end + +-- ===== Подключение ===== + +local function onPlayerAdded(player: Player) + local state = { setup = Buggy.DefaultSetup(), parts = {}, dirty = false, canSave = false, lastChange = 0 } + states[player] = state + publishSetup(player, state) + player:SetAttribute("InGarage", false) + player.CharacterAdded:Connect(function() + player:SetAttribute("InGarage", false) + end) + + if store then + local ok, data = pcall(function() + return store:GetAsync("u" .. player.UserId) + end) + if states[player] ~= state then + return + end + -- Не загрузилось — не сохраняем, чтобы не затереть настоящие данные. + state.canSave = ok + if ok and data then + loadSaved(state, data) + publishSetup(player, state) + if state.room then + refreshDisplay(state) + end + end + end +end + +-- Новая деталь в инвентарь (например, из кейса: { kind = "part", part = id }). +function Garage.GivePart(player: Player, id: string) + local state = states[player] + if state and Config.PartById[id] and not owns(state, id) then + state.parts[id] = true + state.dirty = true + publishSetup(player, state) + end +end + +Cases.Rewards.part = function(player: Player, item) + Garage.GivePart(player, item.part or "") +end + +-- Покупка за осколки: ("part", id) — закрытая деталь, ("paint", номер) — редкая покраска. +local function buy(player: Player, state, kind, key) + if kind == "part" then + local item = typeof(key) == "string" and Config.PartById[key] + if not item or not item.price or owns(state, key) then + return + end + if Shards.Spend(player, item.price) and states[player] == state then + state.parts[key] = true + state.dirty = true + publishSetup(player, state) + task.spawn(save, player, state) -- куплено за валюту — сохраняем сразу + end + elseif kind == "paint" then + local item = typeof(key) == "number" and Config.Garage.Paints[key] + if not item or not item.price or Fortune.HasPaint(player, key) then + return + end + if Shards.Spend(player, item.price) then + Fortune.GivePaint(player, key) + end + end +end + +-- Изменения из меню гаража: ("paint" | "accent", номер), ("equip", id детали), ("unequip", слот), +-- ("buy", "part" | "paint", id или номер). +local function change(player: Player, action, value, extra) + local state = states[player] + if not state then + return + end + local now = os.clock() + if now - state.lastChange < 0.15 then + return + end + + if action == "buy" then + if state.buying then + return + end + state.lastChange = now + state.buying = true -- пока списываем осколки, вторую покупку не принимаем + buy(player, state, value, extra) + state.buying = false + return + end + + local option = typeof(action) == "string" and COLORS[action] + if option then + if typeof(value) ~= "number" or not option.list[value] or state.setup[action] == value then + return + end + if action == "paint" and not Fortune.HasPaint(player, value) then + return -- редкую покраску сначала надо выиграть на колесе + end + state.setup[action] = value + elseif action == "equip" then + local item = typeof(value) == "string" and Config.PartById[value] + if not item or not owns(state, value) or state.setup[item.slot] == value then + return + end + state.setup[item.slot] = value -- что стояло в слоте, само возвращается в инвентарь + elseif action == "unequip" then + local slot = typeof(value) == "string" and SLOTS[value] + if not slot or slot.required or (state.setup[value] or "") == "" then + return -- колёса снять нельзя, только заменить + end + state.setup[value] = "" + else + return + end + + state.lastChange = now + state.dirty = true + publishSetup(player, state) + if state.room then + refreshDisplay(state) + end +end + +local function onPlayerRemoving(player: Player) + local state = states[player] + if not state then + return + end + states[player] = nil + save(player, state) + if state.buggy then + Buggy.Destroy(state.buggy) + end + if state.room then + state.room:Destroy() + usedSlots[state.slot] = nil + end +end + +function Garage.Init(remotes: Folder) + folder = Instance.new("Folder") + folder.Name = "Garages" + folder.Parent = workspace + + local SetupRemote = Instance.new("RemoteEvent") + SetupRemote.Name = "GarageSetup" + SetupRemote.Parent = remotes + local ActionRemote = Instance.new("RemoteEvent") + ActionRemote.Name = "GarageAction" + ActionRemote.Parent = remotes + + Hangar.onDoor = Garage.Enter + + SetupRemote.OnServerEvent:Connect(change) + + ActionRemote.OnServerEvent:Connect(function(player, action) + -- Выезда из гаража нет: багги появляется только на карте команды (см. Lobby). + if action == "leave" and player:GetAttribute("InGarage") then + Garage.Leave(player) + end + end) + + Players.PlayerAdded:Connect(onPlayerAdded) + Players.PlayerRemoving:Connect(onPlayerRemoving) + for _, player in Players:GetPlayers() do + task.spawn(onPlayerAdded, player) + end + game:BindToClose(function() + for player, state in states do + save(player, state) + end + end) + + -- Сохраняем изменения раз в 30 секунд; упавшую с карты багги убираем. + task.spawn(function() + local elapsed = 0 + while true do + task.wait(3) + elapsed += 3 + for player, state in states do + local chassis = state.buggy and state.buggy.PrimaryPart + if state.buggy and (not chassis or not state.buggy.Parent or chassis.Position.Y < -40) then + Buggy.Destroy(state.buggy) + state.buggy = nil + end + if elapsed % 30 == 0 then + task.spawn(save, player, state) + end + end + end + end) +end + +return Garage diff --git a/Zombi/src/server/Hangar.luau b/Zombi/src/server/Hangar.luau new file mode 100644 index 0000000..22c1a3a --- /dev/null +++ b/Zombi/src/server/Hangar.luau @@ -0,0 +1,461 @@ +-- Ангар, где появляются игроки: гофрированные стены, разбитые багги, хлам. +-- По периметру закрытые гаражные ворота — по E игрок попадает в свой личный гараж (см. Garage). + +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage.Shared.Config) +local Buggy = require(script.Parent.Buggy) + +local W = Config.World +local Hangar = {} + +-- Вызывается, когда игрок нажал E у ворот: onDoor(player, doorIndex). Назначает Garage. +Hangar.onDoor = nil :: ((Player, number) -> ())? + +-- { frame = CFrame } — низ ворот по центру стены, LookVector смотрит внутрь ангара. +Hangar.Doors = {} + +local HX, HZ = 52, 36 -- половины размеров ангара +local WALL_H = 22 +local RIDGE = 8 -- конёк крыши выше стен +local DOOR_W, DOOR_H = 12, 10 + +local F = W.BaseHeight + 0.2 -- уровень пола + +-- Центры кругов лобби на полу (круги строит Lobby). Вокруг них не ставим хлам. +Hangar.LobbySpots = { Vector3.new(-26, F, 0), Vector3.new(0, F, -18), Vector3.new(26, F, 0) } +-- Пол ангара (центр в 0, 0): здесь рельеф не нужен, иначе песок вылезает сквозь бетон. +Hangar.FloorSize = Vector3.new(HX * 2 + 2, 0, HZ * 2 + 2) +Hangar.FloorY = F +-- Пьедестал с колесом фортуны (строит Fortune). +Hangar.FortuneSpot = Vector3.new(-10, F, 22) +-- Сюда возвращаются игроки с карт команд. +Hangar.SpawnPoint = CFrame.new(0, F + 3.5, 0) + +local WALL = Color3.fromRGB(96, 84, 70) +local RIB = Color3.fromRGB(70, 62, 54) +local RUST = Color3.fromRGB(122, 72, 42) +local BURNT = Color3.fromRGB(40, 36, 33) +local DARK = Color3.fromRGB(38, 36, 34) +local SHUTTER = Color3.fromRGB(118, 122, 112) +local HAZARD = Color3.fromRGB(220, 175, 40) + +local rng = Random.new(W.Seed + 7) +local folder: Folder + +local function part(props, className: string?): BasePart + local p = Instance.new(className or "Part") + p.Anchored = true + p.TopSurface = Enum.SurfaceType.Smooth + p.BottomSurface = Enum.SurfaceType.Smooth + for k, v in props do + p[k] = v + end + p.Parent = p.Parent or folder + return p +end + +local function sign(parent: BasePart, face: Enum.NormalId, text: string, textSize: number) + local gui = Instance.new("SurfaceGui") + gui.Face = face + gui.SizingMode = Enum.SurfaceGuiSizingMode.PixelsPerStud + gui.PixelsPerStud = 40 + gui.LightInfluence = 0.3 + gui.Parent = parent + local label = Instance.new("TextLabel") + label.Size = UDim2.fromScale(1, 1) + label.BackgroundTransparency = 1 + label.Font = Enum.Font.GothamBlack + label.TextSize = textSize + label.TextColor3 = HAZARD + label.Text = text + label.Parent = gui +end + +-- ===== Ворота ===== + +local function garageDoor(frame: CFrame, index: number) + local shutter = part({ + Name = "GarageDoor", + Size = Vector3.new(DOOR_W, DOOR_H, 0.4), + CFrame = frame * CFrame.new(0, DOOR_H / 2, 0), + Color = SHUTTER:Lerp(RUST, rng:NextNumber(0, 0.5)), + Material = Enum.Material.CorrodedMetal, + }) + -- Секции рулонной шторы + for y = 1, DOOR_H - 1 do + part({ Size = Vector3.new(DOOR_W, 0.12, 0.6), CFrame = frame * CFrame.new(0, y, 0), Color = RIB, Material = Enum.Material.Metal, CanCollide = false }) + end + part({ Size = Vector3.new(2.4, 0.3, 0.8), CFrame = frame * CFrame.new(0, 0.7, 0), Color = DARK, Material = Enum.Material.Metal, CanCollide = false }) + -- Рама в жёлто-чёрную полоску + for _, x in { -1, 1 } do + part({ Size = Vector3.new(0.8, DOOR_H + 0.8, 1.4), CFrame = frame * CFrame.new(x * (DOOR_W / 2 + 0.4), (DOOR_H + 0.8) / 2, 0), Color = DARK, Material = Enum.Material.Metal }) + for y = 1, DOOR_H, 2 do + part({ Size = Vector3.new(0.85, 0.9, 1.45), CFrame = frame * CFrame.new(x * (DOOR_W / 2 + 0.4), y, 0) * CFrame.Angles(0, 0, math.rad(30)), Color = HAZARD, Material = Enum.Material.Metal, CanCollide = false }) + end + end + part({ Size = Vector3.new(DOOR_W + 1.6, 0.8, 1.4), CFrame = frame * CFrame.new(0, DOOR_H + 0.4, 0), Color = DARK, Material = Enum.Material.Metal }) + -- Короб для шторы и номер ворот с обеих сторон + part({ Size = Vector3.new(DOOR_W + 1, 1.4, 2.2), CFrame = frame * CFrame.new(0, DOOR_H + 1.5, 0), Color = SHUTTER:Lerp(DARK, 0.5), Material = Enum.Material.CorrodedMetal }) + local plate = part({ Size = Vector3.new(5, 1.5, 2.4), CFrame = frame * CFrame.new(0, DOOR_H + 3.1, 0), Color = DARK, Material = Enum.Material.Metal }) + local caption = ("ГАРАЖ %02d"):format(index) + sign(plate, Enum.NormalId.Front, caption, 34) + sign(plate, Enum.NormalId.Back, caption, 34) + local lamp = part({ Shape = Enum.PartType.Ball, Size = Vector3.new(0.7, 0.7, 0.7), CFrame = frame * CFrame.new(DOOR_W / 2 + 0.4, DOOR_H + 1.3, 0), Color = Color3.fromRGB(255, 150, 40), Material = Enum.Material.Neon, CanCollide = false }) + local light = Instance.new("PointLight") + light.Color = Color3.fromRGB(255, 150, 60) + light.Range = 12 + light.Brightness = 1.5 + light.Parent = lamp + -- Разметка перед воротами внутри + part({ Size = Vector3.new(DOOR_W, 0.06, 0.8), CFrame = frame * CFrame.new(0, 0.03, -2), Color = HAZARD, Material = Enum.Material.SmoothPlastic, CanCollide = false }) + + -- Подсказка видна с обеих сторон стены: можно зайти и из ангара, и подъехав снаружи. + local prompt = Instance.new("ProximityPrompt") + prompt.Name = "GaragePrompt" + prompt.ActionText = "Войти в свой гараж" + prompt.ObjectText = caption + prompt.KeyboardKeyCode = Enum.KeyCode.E + prompt.HoldDuration = 0.3 + prompt.MaxActivationDistance = 10 + prompt.RequiresLineOfSight = false + prompt.Parent = shutter + prompt.Triggered:Connect(function(player) + if Hangar.onDoor then + Hangar.onDoor(player, index) + end + end) +end + +-- center — середина стены на уровне пола: X — вдоль стены, LookVector — внутрь ангара. +local function wall(center: CFrame, length: number, doorOffsets: { number }) + local function panel(a: number, b: number, y0: number, y1: number) + if b - a > 0.05 then + part({ Size = Vector3.new(b - a, y1 - y0, 1), CFrame = center * CFrame.new((a + b) / 2, (y0 + y1) / 2, 0), Color = WALL, Material = Enum.Material.CorrodedMetal }) + end + end + local cursor = -length / 2 + for _, d in doorOffsets do + panel(cursor, d - DOOR_W / 2, 0, WALL_H) + panel(d - DOOR_W / 2, d + DOOR_W / 2, DOOR_H, WALL_H) + cursor = d + DOOR_W / 2 + end + panel(cursor, length / 2, 0, WALL_H) + + -- Рёбра гофры с обеих сторон + for x = -length / 2 + 2, length / 2 - 2, 4 do + local bottom = 0 + for _, d in doorOffsets do + if math.abs(x - d) < DOOR_W / 2 + 1.2 then + bottom = DOOR_H + 2.2 + end + end + for _, side in { -0.65, 0.65 } do + part({ Size = Vector3.new(0.5, WALL_H - bottom, 0.3), CFrame = center * CFrame.new(x, (bottom + WALL_H) / 2, side), Color = RIB, Material = Enum.Material.CorrodedMetal, CanCollide = false }) + end + end + + for i, d in doorOffsets do + local frame = center * CFrame.new(d, 0, 0) + table.insert(Hangar.Doors, { frame = frame }) + garageDoor(frame, #Hangar.Doors) + end +end + +-- ===== Разбитые багги ===== + +local function stripWheel(model: Model, name: string) + for _, suffix in { "Wheel", "Rim", "Spoke" } do + local p = model:FindFirstChild(name .. suffix) + if p then + p:Destroy() + end + end +end + +-- Редкие покраски — только с колеса фортуны, у разбитых багги их не бывает. +local basicPaints = 0 +for _, paint in Config.Garage.Paints do + if not paint.rare then + basicPaints += 1 + end +end + +-- Детали для разбитых багги по слотам. Без гусениц: у обломков снимаем колёса, а лента бы повисла в воздухе. +local wreckParts = {} +for _, item in Config.Garage.Parts do + if not item.tracks then + wreckParts[item.slot] = wreckParts[item.slot] or {} + table.insert(wreckParts[item.slot], item.id) + end +end + +local function randomPart(slot: string, emptyChance: number): string + local list = wreckParts[slot] + if not list or rng:NextNumber() < emptyChance then + return "" + end + return list[rng:NextInteger(1, #list)] +end + +local function randomSetup() + return { + paint = rng:NextInteger(1, basicPaints), + accent = rng:NextInteger(1, #Config.Garage.Accents), + front = randomPart("front", 0.25), + wheels = randomPart("wheels", 0), + rear = randomPart("rear", 0.5), + armor = randomPart("armor", 0.6), + weapon = randomPart("weapon", 0), + } +end + +local function burn(at: BasePart, size: number) + local fire = Instance.new("Fire") + fire.Size = size + fire.Heat = 6 + fire.Parent = at + local light = Instance.new("PointLight") + light.Color = Color3.fromRGB(255, 130, 50) + light.Range = 16 + light.Brightness = 2 + light.Parent = at +end + +-- variant: stands — без колёс на домкратах, flipped — вверх колёсами, noseDown — без передних колёс, +-- tilted — завалилась набок, burnt — сгоревшая, stripped — без колёс лежит на полу. +local function wreck(x: number, z: number, heading: number, variant: string) + -- Модель для витрины висит на 0.3 над землёй (запас на подвеску) — опускаем. + local ground = CFrame.new(x, F - 0.3, z) * CFrame.Angles(0, heading, 0) + local model = Buggy.Build(ground, { display = true, setup = randomSetup(), parent = folder }) + model.Name = "Wreck" + + local burnt = if variant == "burnt" then 0.85 else rng:NextNumber(0.25, 0.55) + for _, d in model:GetDescendants() do + if d:IsA("BasePart") and d.Transparency < 1 then + if d.Material == Enum.Material.Neon then + d.Material = Enum.Material.Glass + d.Color = DARK + else + d.Color = d.Color:Lerp(BURNT, burnt) + end + elseif d:IsA("Light") or d:IsA("Smoke") then + d:Destroy() + end + end + + local chassis = model.PrimaryPart + local c = chassis.CFrame + local height = c.Y - F -- центр рамы над полом + + 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)) + 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) + 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 + end + 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)) + 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) + 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) + 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 }) + burn(engine, 5) + end + if variant ~= "burnt" and rng:NextNumber() < 0.5 then + local smoke = Instance.new("Smoke") + smoke.Color = Color3.fromRGB(50, 46, 42) + smoke.Opacity = 0.12 + smoke.RiseVelocity = 3 + smoke.Size = 2 + smoke.Parent = chassis + end +end + +-- ===== Хлам ===== + +local function tire(cf: CFrame) + part({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(1.3, 3.4, 3.4), CFrame = cf, Color = Color3.fromRGB(24, 24, 24), Material = Enum.Material.Fabric }) +end + +local function tireStack(x: number, z: number) + for i = 1, rng:NextInteger(3, 6) do + tire(CFrame.new(x + rng:NextNumber(-0.3, 0.3), F + 0.65 + (i - 1) * 1.3, z) * CFrame.Angles(0, rng:NextNumber(0, 3), math.pi / 2)) + end +end + +local function workbench(cf: CFrame) + part({ Size = Vector3.new(8, 0.4, 3), CFrame = cf * CFrame.new(0, 3.2, 0), Color = Color3.fromRGB(90, 66, 44), Material = Enum.Material.WoodPlanks }) + for _, x in { -3.6, 3.6 } do + for _, z in { -1.2, 1.2 } do + part({ Size = Vector3.new(0.4, 3, 0.4), CFrame = cf * CFrame.new(x, 1.5, z), Color = DARK, Material = Enum.Material.Metal }) + end + end + part({ Size = Vector3.new(2, 1, 1.2), CFrame = cf * CFrame.new(-2, 3.9, 0), Color = Color3.fromRGB(170, 40, 30), Material = Enum.Material.Metal }) + part({ Size = Vector3.new(1.4, 1.6, 1.4), CFrame = cf * CFrame.new(2.4, 4.2, 0.2), Color = DARK, Material = Enum.Material.Metal }) +end + +local function engineBlock(cf: CFrame) + part({ Size = Vector3.new(3, 2.2, 3.6), CFrame = cf * CFrame.new(0, 1.1, 0), Color = DARK:Lerp(RUST, 0.4), Material = Enum.Material.CorrodedMetal }) + part({ Size = Vector3.new(2.4, 0.8, 3.2), CFrame = cf * CFrame.new(0, 2.6, 0), Color = DARK, Material = Enum.Material.Metal }) +end + +local function ceilingLamp(x: number, z: number): PointLight + local lamp = part({ Size = Vector3.new(5, 0.4, 1.2), CFrame = CFrame.new(x, F + 18, z), Color = Color3.fromRGB(255, 225, 170), Material = Enum.Material.Neon, CanCollide = false }) + part({ Size = Vector3.new(5.4, 0.5, 1.6), CFrame = CFrame.new(x, F + 18.4, z), Color = DARK, Material = Enum.Material.Metal, CanCollide = false }) + for _, dx in { -2, 2 } do + part({ Size = Vector3.new(0.1, WALL_H - 18.5, 0.1), CFrame = CFrame.new(x + dx, F + (WALL_H + 18.5) / 2, z), Color = DARK, Material = Enum.Material.Metal, CanCollide = false }) + end + local light = Instance.new("PointLight") + light.Color = Color3.fromRGB(255, 215, 160) + light.Range = 36 + light.Brightness = 0.8 + light.Shadows = true + light.Parent = lamp + return light +end + +-- ===== Сборка ===== + +function Hangar.Build() + folder = Instance.new("Folder") + folder.Name = "Hangar" + folder.Parent = workspace + + for _, old in workspace:GetChildren() do + if old:IsA("SpawnLocation") or old.Name == "Baseplate" then + old:Destroy() + end + end + + -- Пол с масляными пятнами + part({ Name = "Floor", Size = Vector3.new(HX * 2 + 2, 1, HZ * 2 + 2), CFrame = CFrame.new(0, F - 0.5, 0), Color = Color3.fromRGB(105, 100, 94), Material = Enum.Material.Concrete }) + for _ = 1, 14 do + local s = rng:NextNumber(3, 9) + part({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.05, s, s * rng:NextNumber(0.6, 1)), CFrame = CFrame.new(rng:NextNumber(-HX + 6, HX - 6), F + 0.02, rng:NextNumber(-HZ + 6, HZ - 6)) * CFrame.Angles(0, rng:NextNumber(0, 3), math.pi / 2), Color = Color3.fromRGB(35, 32, 30), Material = Enum.Material.SmoothPlastic, Transparency = 0.35, CanCollide = false }) + end + + -- Стены с воротами: по 4 на длинных стенах, по 2 на торцах. + local up = Vector3.yAxis + wall(CFrame.lookAt(Vector3.new(0, F, -HZ), Vector3.new(0, F, 0), up), HX * 2 + 1, { -36, -12, 12, 36 }) + wall(CFrame.lookAt(Vector3.new(0, F, HZ), Vector3.new(0, F, 0), up), HX * 2 + 1, { -36, -12, 12, 36 }) + wall(CFrame.lookAt(Vector3.new(-HX, F, 0), Vector3.new(0, F, 0), up), HZ * 2 - 1, { -14, 14 }) + wall(CFrame.lookAt(Vector3.new(HX, F, 0), Vector3.new(0, F, 0), up), HZ * 2 - 1, { -14, 14 }) + + -- Двускатная крыша с парой прогнивших дыр — сквозь них падают лучи солнца. + local slope = math.atan(RIDGE / HZ) + local slopeLength = math.sqrt(HZ * HZ + RIDGE * RIDGE) + 1.5 + local segment = (HX * 2 + 2) / 8 + for side = -1, 1, 2 do + for i = 0, 7 do + local hole = (side == -1 and i == 2) or (side == 1 and i == 5) + local x = -HX - 1 + segment * (i + 0.5) + local cf = CFrame.new(x, F + WALL_H + RIDGE / 2, side * HZ / 2) * CFrame.Angles(side * slope, 0, 0) + if hole then + -- Остались только края листа + part({ Size = Vector3.new(segment, 0.5, slopeLength * 0.35), CFrame = cf * CFrame.new(0, 0, side * slopeLength * 0.325), Color = RUST, Material = Enum.Material.CorrodedMetal }) + part({ Size = Vector3.new(segment * 0.4, 0.5, slopeLength * 0.3), CFrame = cf * CFrame.new(segment * 0.3, 0, -side * slopeLength * 0.1), Color = RUST, Material = Enum.Material.CorrodedMetal }) + else + part({ Size = Vector3.new(segment, 0.5, slopeLength), CFrame = cf, Color = WALL:Lerp(RUST, rng:NextNumber(0, 0.6)), Material = Enum.Material.CorrodedMetal }) + end + end + end + -- Фронтоны над торцевыми стенами + for _, x in { -HX, HX } do + part({ Size = Vector3.new(1, RIDGE, HZ), CFrame = CFrame.new(x, F + WALL_H + RIDGE / 2, -HZ / 2), Color = WALL, Material = Enum.Material.CorrodedMetal }, "WedgePart") + part({ Size = Vector3.new(1, RIDGE, HZ), CFrame = CFrame.new(x, F + WALL_H + RIDGE / 2, HZ / 2) * CFrame.Angles(0, math.pi, 0), Color = WALL, Material = Enum.Material.CorrodedMetal }, "WedgePart") + end + -- Фермы под крышей + for x = -39, 39, 13 do + part({ Size = Vector3.new(0.8, 0.8, HZ * 2), CFrame = CFrame.new(x, F + WALL_H - 0.4, 0), Color = RUST, Material = Enum.Material.CorrodedMetal }) + part({ Size = Vector3.new(0.6, RIDGE, 0.6), CFrame = CFrame.new(x, F + WALL_H + RIDGE / 2, 0), Color = RUST, Material = Enum.Material.CorrodedMetal }) + end + + -- Свет: лампы под фермами, одна мигает. + local lights = {} + for _, x in { -26, 0, 26 } do + for _, z in { -14, 14 } do + table.insert(lights, ceilingLamp(x, z)) + end + end + local flicker = lights[rng:NextInteger(1, #lights)] + task.spawn(function() + while flicker.Parent do + flicker.Enabled = rng:NextNumber() > 0.25 + flicker.Parent.Transparency = flicker.Enabled and 0 or 0.7 + task.wait(rng:NextNumber(0.05, 0.6)) + end + end) + + -- Баннеры + for z, text in { [-HZ + 0.6] = "ВСТАНЬ В КРУГ · СОБЕРИ КОМАНДУ", [HZ - 0.6] = "ПОДОЙДИ К ВОРОТАМ · [E] — ТВОЙ ГАРАЖ" } do + local banner = part({ Size = Vector3.new(30, 3, 0.2), CFrame = CFrame.lookAt(Vector3.new(0, F + 15, z), Vector3.new(0, F + 15, 0)), Color = DARK, Material = Enum.Material.Metal, CanCollide = false }) + sign(banner, Enum.NormalId.Front, text, 64) + end + + -- Разбитые багги + wreck(-30, -14, 0.4, "stands") + wreck(-28, 14, -0.9, "noseDown") + wreck(26, -14, 2.6, "flipped") + wreck(30, 14, -2.2, "tilted") + wreck(6, 20, math.pi / 2, "stripped") + wreck(-42, 0, 0, "noseDown") + wreck(42, 0, math.pi, "burnt") + + -- Хлам по углам и у стен + for _, spot in { { -47, -31 }, { 47, -31 }, { -47, 31 }, { 47, 31 }, { 0, -31 }, { 24, 31 } } do + tireStack(spot[1], spot[2]) + end + for _ = 1, 10 do + local at = Vector3.new(rng:NextNumber(-HX + 8, HX - 8), F + 0.65, rng:NextNumber(-HZ + 10, HZ - 10)) + local free = (at - Hangar.FortuneSpot).Magnitude > 8 + for _, spot in Hangar.LobbySpots do + if (at - spot).Magnitude < Config.Lobby.Radius + 3 then + free = false + end + end + if free then + tire(CFrame.new(at) * CFrame.Angles(0, rng:NextNumber(0, 3), math.pi / 2)) + end + end + workbench(CFrame.new(-24, F, -32)) + workbench(CFrame.new(-24, F, 32) * CFrame.Angles(0, math.pi, 0)) + engineBlock(CFrame.new(16, F, -6) * CFrame.Angles(0, 0.7, 0)) + engineBlock(CFrame.new(-14, F, 6) * CFrame.Angles(0, -0.3, 0)) + + local spawn = Instance.new("SpawnLocation") + spawn.Anchored = true + spawn.Size = Vector3.new(10, 0.4, 10) + spawn.CFrame = CFrame.new(0, F + 0.2, 0) + spawn.Color = RUST + spawn.Material = Enum.Material.DiamondPlate + spawn.Duration = 0 + spawn.Parent = folder +end + +return Hangar diff --git a/Zombi/src/server/Loading.luau b/Zombi/src/server/Loading.luau new file mode 100644 index 0000000..d056075 --- /dev/null +++ b/Zombi/src/server/Loading.luau @@ -0,0 +1,60 @@ +-- Экран загрузки при переходе между зонами (ангар, гараж, пустошь, карта команды). +-- Порядок: клиент затемняет экран → сервер переносит персонажа и держит его на месте → +-- клиент подгружает сцену вокруг (детали, текстуры, свет) → персонаж отпускается, экран гаснет. +-- Сам экран — Loading.client в ReplicatedFirst. + +local Players = game:GetService("Players") + +local Loading = {} + +local Remote: RemoteEvent +local pending = {} -- [Player] = { token, ready, loaded } +local counter = 0 + +local function waitFor(player: Player, token: number, stage: string, timeout: number) + local deadline = os.clock() + timeout + while os.clock() < deadline and player.Parent do + local p = pending[player] + if not p or p.token ~= token or p[stage] then + return + end + task.wait(0.05) + end +end + +-- Затемнить экран игрока. Возвращает, когда экран чёрный (или вышло время). +function Loading.Begin(player: Player, text: string): number + counter += 1 + local token = counter + pending[player] = { token = token } + Remote:FireClient(player, "show", token, text) + waitFor(player, token, "ready", 1.5) + return token +end + +-- Персонаж уже на месте: ждём, пока клиент подгрузит сцену вокруг position. +function Loading.Finish(player: Player, token: number, position: Vector3) + Remote:FireClient(player, "arrived", token, position) + waitFor(player, token, "loaded", 12) + local p = pending[player] + if p and p.token == token then + pending[player] = nil + end +end + +function Loading.Init(remotes: Folder) + Remote = Instance.new("RemoteEvent") + Remote.Name = "Loading" + Remote.Parent = remotes + Remote.OnServerEvent:Connect(function(player, stage, token) + local p = pending[player] + if p and p.token == token and (stage == "ready" or stage == "loaded") then + p[stage] = true + end + end) + Players.PlayerRemoving:Connect(function(player) + pending[player] = nil + end) +end + +return Loading diff --git a/Zombi/src/server/Lobby.luau b/Zombi/src/server/Lobby.luau new file mode 100644 index 0000000..c271a5d --- /dev/null +++ b/Zombi/src/server/Lobby.luau @@ -0,0 +1,357 @@ +-- Лобби в ангаре: три круга с прозрачными цветными стенками. +-- Встал в пустой круг — можно создать лобби на 1–4 игрока; встал в круг с открытым лобби — вступить. +-- Кто в лобби, не выйдет из круга (стенки для него твёрдые на клиенте, а сервер ещё и возвращает назад), +-- пока создатель не закроет лобби или сам игрок его не покинет. +-- Лобби заполнилось — обратный отсчёт, и команда выезжает на свою карту (у каждого круга своя, см. World.Arenas). +-- Пока команда на карте, круг занят. + +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage.Shared.Config) +local Garage = require(script.Parent.Garage) +local Hangar = require(script.Parent.Hangar) +local World = require(script.Parent.World) +local Zombies = require(script.Parent.Zombies) + +local L = Config.Lobby +local Lobby = {} + +local SEGMENTS = 28 -- из скольких панелей собрана стенка круга +local DARK = Color3.fromRGB(38, 36, 34) + +-- status: "free" — никого, "open" — набор, "starting" — полное, идёт отсчёт, "playing" — команда на карте. +-- owner — создатель, members — все в лобби (создатель первый), arena — [Player] = true, кто сейчас на карте. +-- token меняется при каждом изменении состава — так отменяется устаревший отсчёт. +local circles = {} +local lastAction = {} -- [Player] = os.clock() + +local function part(parent: Instance, props): BasePart + local p = Instance.new("Part") + p.Anchored = true + p.CanCollide = false + p.CanTouch = false + p.CastShadow = false + p.TopSurface = Enum.SurfaceType.Smooth + p.BottomSurface = Enum.SurfaceType.Smooth + for k, v in props do + p[k] = v + end + p.Parent = parent + return p +end + +-- ===== Круг ===== + +local function buildCircle(index: number, center: Vector3) + local R, H = L.Radius, L.WallHeight + local color = L.Colors[index] or L.Colors[1] + local model = Instance.new("Model") + model.Name = "Lobby" .. index + model:SetAttribute("Index", index) + + -- Светящееся кольцо на полу и тёмный круг внутри + local disc = CFrame.new(center) * CFrame.Angles(0, 0, math.pi / 2) + part(model, { Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.1, R * 2, R * 2), CFrame = disc * CFrame.new(0.05, 0, 0), Color = color, Material = Enum.Material.Neon, Transparency = 0.6 }) + part(model, { Shape = Enum.PartType.Cylinder, Size = Vector3.new(0.12, R * 2 - 1, R * 2 - 1), CFrame = disc * CFrame.new(0.06, 0, 0), Color = DARK, Material = Enum.Material.SmoothPlastic, Transparency = 0.25 }) + + -- Стенки: на сервере проходимые, клиент делает их твёрдыми для участников лобби. + local walls = Instance.new("Folder") + walls.Name = "Walls" + walls.Parent = model + local width = 2 * R * math.tan(math.pi / SEGMENTS) + 0.05 + for i = 0, SEGMENTS - 1 do + local around = CFrame.new(center) * CFrame.Angles(0, i / SEGMENTS * math.pi * 2, 0) + part(walls, { Name = "Wall", Size = Vector3.new(width, H, 0.3), CFrame = around * CFrame.new(0, H / 2, -R), Color = color, Material = Enum.Material.Glass, Transparency = 0.7, CanQuery = false }) + part(model, { Size = Vector3.new(width, 0.25, 0.4), CFrame = around * CFrame.new(0, H, -R), Color = color, Material = Enum.Material.Neon, Transparency = 0.45, CanQuery = false }) + end + + -- Табличка над кругом + local anchor = part(model, { Name = "Sign", Size = Vector3.new(1, 1, 1), CFrame = CFrame.new(center + Vector3.new(0, H + 3, 0)), Transparency = 1, CanQuery = false }) + local board = Instance.new("BillboardGui") + board.Size = UDim2.fromScale(12, 3.6) + board.MaxDistance = 120 + board.LightInfluence = 0 + board.Parent = anchor + local title = Instance.new("TextLabel") + title.Name = "Title" + title.BackgroundTransparency = 1 + title.Size = UDim2.fromScale(1, 0.55) + title.Font = Enum.Font.GothamBlack + title.TextScaled = true + title.TextColor3 = color + title.TextStrokeTransparency = 0.4 + title.Parent = board + local status = title:Clone() + status.Name = "Status" + status.Position = UDim2.fromScale(0, 0.58) + status.Size = UDim2.fromScale(1, 0.4) + status.Font = Enum.Font.GothamBold + status.TextColor3 = Color3.fromRGB(235, 220, 200) + status.Parent = board + + model.Parent = workspace:FindFirstChild("Lobbies") + circles[index] = { + index = index, + center = center, + model = model, + title = title, + statusLabel = status, + status = "free", + owner = nil :: Player?, + size = 0, + members = {} :: { Player }, + arena = {} :: { [Player]: boolean }, + token = 0, + } +end + +-- Состояние круга — в атрибуты модели: по ним клиент рисует меню. +local function publish(circle) + local m = circle.model + local names = {} + for _, member in circle.members do + table.insert(names, member.DisplayName) + end + local onMap = 0 + for _ in circle.arena do + onMap += 1 + end + m:SetAttribute("Status", circle.status) + m:SetAttribute("OwnerId", if circle.owner then circle.owner.UserId else 0) + m:SetAttribute("OwnerName", if circle.owner then circle.owner.DisplayName else "") + m:SetAttribute("Size", circle.size) + m:SetAttribute("Count", #circle.members) + m:SetAttribute("Members", table.concat(names, "\n")) + m:SetAttribute("OnMap", onMap) + + if circle.status == "free" then + circle.title.Text = "ЛОББИ " .. circle.index + circle.statusLabel.Text = "свободно · встань в круг" + elseif circle.status == "playing" then + circle.title.Text = "ЛОББИ " .. circle.index + circle.statusLabel.Text = ("команда на карте · %d"):format(onMap) + else + circle.title.Text = string.upper(circle.owner.DisplayName) + circle.statusLabel.Text = if circle.status == "starting" then "старт!" else ("игроков %d / %d"):format(#circle.members, circle.size) + end +end + +local function launch(circle) + local team = circle.members + circle.members, circle.owner, circle.size = {}, nil, 0 + circle.token += 1 + circle.status = "playing" + 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) + end + Zombies.Start(circle.index) + publish(circle) +end + +-- После любого изменения состава или размера: заполнилось — запускаем отсчёт, освободилось место — отменяем. +local function update(circle) + if circle.status == "open" and #circle.members >= circle.size then + circle.status = "starting" + circle.token += 1 + local token = circle.token + circle.model:SetAttribute("StartAt", workspace:GetServerTimeNow() + L.Countdown) + task.spawn(function() + task.wait(L.Countdown) + -- Карты строятся после запуска сервера — если эта ещё не готова, ждём. + while circle.token == token and not World.ArenaReady(circle.index) do + task.wait(0.5) + end + if circle.token == token then + launch(circle) + end + end) + elseif circle.status == "starting" and #circle.members < circle.size then + circle.status = "open" + circle.token += 1 + end + publish(circle) +end + +-- Закрыть лобби: все участники свободны. +local function close(circle) + for _, member in circle.members do + member:SetAttribute("Lobby", 0) + end + circle.members, circle.owner, circle.size = {}, nil, 0 + circle.token += 1 + circle.status = if next(circle.arena) then "playing" else "free" + publish(circle) +end + +local function lobbyOf(player: Player) + return circles[player:GetAttribute("Lobby") or 0] +end + +local function removeMember(player: Player) + local circle = lobbyOf(player) + if not circle then + return + end + if circle.owner == player then + close(circle) + return + end + local i = table.find(circle.members, player) + if i then + table.remove(circle.members, i) + end + player:SetAttribute("Lobby", 0) + update(circle) +end + +local function leaveArena(player: Player, toHangar: boolean) + local circle = circles[player:GetAttribute("Arena") or 0] + player:SetAttribute("Arena", 0) + Garage.RemoveBuggy(player) + if toHangar then + task.spawn(Garage.Teleport, player, Hangar.SpawnPoint, "Ангар") + end + if circle and circle.arena[player] then + circle.arena[player] = nil + if circle.status == "playing" and not next(circle.arena) then + circle.status = "free" + Zombies.Stop(circle.index) -- вся команда ушла с карты + end + publish(circle) + end +end + +local function validSize(value): boolean + return typeof(value) == "number" and value % 1 == 0 and value >= 1 and value <= L.MaxPlayers +end + +-- ===== Действия игрока ===== + +local function onAction(player: Player, action, value) + local now = os.clock() + if lastAction[player] and now - lastAction[player] < 0.25 then + return + end + lastAction[player] = now + + local free = not lobbyOf(player) and (player:GetAttribute("Arena") or 0) == 0 + local standing = circles[player:GetAttribute("LobbyIn") or 0] + local own = lobbyOf(player) + + if action == "create" then + if free and standing and standing.status == "free" and validSize(value) then + standing.owner = player + standing.size = value + standing.members = { player } + standing.status = "open" + player:SetAttribute("Lobby", standing.index) + update(standing) + end + elseif action == "join" then + if free and standing and standing.status == "open" and #standing.members < standing.size then + table.insert(standing.members, player) + player:SetAttribute("Lobby", standing.index) + update(standing) + end + elseif action == "size" then + -- Меньше, чем уже в лобби, поставить нельзя. + if own and own.owner == player and validSize(value) and value >= #own.members and own.size ~= value then + own.size = value + update(own) + end + elseif action == "leave" then + if own and own.owner ~= player then + removeMember(player) + end + elseif action == "close" then + if own and own.owner == player then + close(own) + end + elseif action == "return" then + if (player:GetAttribute("Arena") or 0) > 0 then + leaveArena(player, true) + end + end +end + +-- Кто в каком круге стоит; участников лобби, выбравшихся наружу, возвращаем в их круг. +local function watch() + for _, player in Players:GetPlayers() do + local character = player.Character + local root = character and character:FindFirstChild("HumanoidRootPart") :: BasePart? + local humanoid = character and character:FindFirstChildOfClass("Humanoid") + local inside = 0 + if root and humanoid and humanoid.Health > 0 then + for index, circle in circles do + local offset = root.Position - circle.center + if Vector3.new(offset.X, 0, offset.Z).Magnitude <= L.Radius and offset.Y > -2 and offset.Y < L.WallHeight + 4 then + inside = index + end + end + local own = lobbyOf(player) + if own and inside ~= own.index then + local flat = (root.Position - own.center) * Vector3.new(1, 0, 1) + local dir = if flat.Magnitude > 0.1 then flat.Unit else Vector3.zAxis + local at = own.center + dir * (L.Radius - 1.5) + Vector3.new(0, 3.5, 0) + task.spawn(Garage.Teleport, player, CFrame.lookAt(at, Vector3.new(own.center.X, at.Y, own.center.Z))) + inside = own.index + end + end + if player:GetAttribute("LobbyIn") ~= inside then + player:SetAttribute("LobbyIn", inside) + end + end +end + +-- ===== Подключение ===== + +local function onPlayerAdded(player: Player) + player:SetAttribute("Lobby", 0) + player:SetAttribute("LobbyIn", 0) + player:SetAttribute("Arena", 0) + -- Погиб на карте команды — появляется в ангаре, на карту уже не вернуться. + player.CharacterAdded:Connect(function() + if (player:GetAttribute("Arena") or 0) > 0 then + leaveArena(player, false) + end + end) +end + +function Lobby.Init(remotes: Folder) + local folder = Instance.new("Folder") + folder.Name = "Lobbies" + folder.Parent = workspace + for index, spot in Hangar.LobbySpots do + buildCircle(index, spot) + publish(circles[index]) + end + + local ActionRemote = Instance.new("RemoteEvent") + ActionRemote.Name = "LobbyAction" + ActionRemote.Parent = remotes + ActionRemote.OnServerEvent:Connect(onAction) + + Players.PlayerAdded:Connect(onPlayerAdded) + Players.PlayerRemoving:Connect(function(player) + removeMember(player) + leaveArena(player, false) + lastAction[player] = nil + end) + for _, player in Players:GetPlayers() do + task.spawn(onPlayerAdded, player) + end + + task.spawn(function() + while true do + task.wait(0.15) + watch() + end + end) +end + +return Lobby diff --git a/Zombi/src/server/Main.server.luau b/Zombi/src/server/Main.server.luau new file mode 100644 index 0000000..4929f0f --- /dev/null +++ b/Zombi/src/server/Main.server.luau @@ -0,0 +1,56 @@ +-- Точка входа сервера: ангар со входами в личные гаражи и кругами лобби, пустошь, карты команд, пулемёты. + +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") +local StarterPlayer = game:GetService("StarterPlayer") + +local Config = require(ReplicatedStorage.Shared.Config) + +-- Камеру далеко не отдалить: за краем карты и над туманом смотреть не на что (см. EdgeFog.client). +StarterPlayer.CameraMaxZoomDistance = Config.World.CameraMaxZoom +for _, player in Players:GetPlayers() do + player.CameraMaxZoomDistance = Config.World.CameraMaxZoom +end +local World = require(script.Parent.World) +local Buggy = require(script.Parent.Buggy) +local Weapons = require(script.Parent.Weapons) +local Garage = require(script.Parent.Garage) +local Lobby = require(script.Parent.Lobby) +local Fortune = require(script.Parent.Fortune) +local Cases = require(script.Parent.Cases) +local Shards = require(script.Parent.Shards) +local Loading = require(script.Parent.Loading) +local Zombies = require(script.Parent.Zombies) + +local remotes = Instance.new("Folder") +remotes.Name = "Remotes" +local FlipBuggy = Instance.new("RemoteEvent") +FlipBuggy.Name = "FlipBuggy" +FlipBuggy.Parent = remotes +Loading.Init(remotes) +Shards.Init() +Zombies.Init(remotes) +Weapons.Init(remotes) +Garage.Init(remotes) +Lobby.Init(remotes) +Fortune.Init(remotes) +Cases.Init(remotes) +remotes.Parent = ReplicatedStorage + +Buggy.Start() + +local lastFlip = {} -- [Player] = os.clock() +FlipBuggy.OnServerEvent:Connect(function(player) + local now = os.clock() + if lastFlip[player] and now - lastFlip[player] < Config.FlipCooldown then + return + end + lastFlip[player] = now + local model = Buggy.FindDrivenBy(player) + if model then + Buggy.Flip(model) + end +end) + +World.BuildHangar() +World.BuildMaps() -- последним: строит рельеф всех карт, несколько секунд на каждую diff --git a/Zombi/src/server/Shards.luau b/Zombi/src/server/Shards.luau new file mode 100644 index 0000000..07262f3 --- /dev/null +++ b/Zombi/src/server/Shards.luau @@ -0,0 +1,125 @@ +-- Осколки — внутриигровая валюта. Баланс в атрибуте игрока Shards. +-- Каждое изменение сразу пишется в DataStore через UpdateAsync (как у кейсов): трата не уйдёт в минус +-- и не потеряется, даже если сервер упадёт сразу после покупки. + +local DataStoreService = game:GetService("DataStoreService") +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage.Shared.Config) +local Cases = require(script.Parent.Cases) + +local Shards = {} + +local store: DataStore? = nil +pcall(function() + store = DataStoreService:GetDataStore("Shards_v1") +end) + +-- [userId] = { balance, loaded, canSave } +local states = {} + +-- Новый игрок начинает со стартовым запасом. +local function normalize(data): number + if typeof(data) == "table" and typeof(data.balance) == "number" then + return math.max(0, math.floor(data.balance)) + end + return Config.Shards.Start +end + +local function publish(userId: number) + local player = Players:GetPlayerByUserId(userId) + local s = states[userId] + if player and s then + player:SetAttribute("Shards", s.balance) + end +end + +-- delta > 0 — начислить, < 0 — списать (только если хватает). Возвращает, прошла ли операция. +-- Работает и для игрока не в сети. +local function change(userId: number, delta: number): boolean + local s = states[userId] + -- Игрок только зашёл: ждём загрузку, иначе она затрёт изменение старым балансом. + local deadline = os.clock() + 15 + while s and not s.loaded and os.clock() < deadline do + task.wait(0.1) + end + if s and not s.loaded then + return false + end + if store and (not s or s.canSave) then + local applied = false + local ok, result = pcall(function() + return store:UpdateAsync("u" .. userId, function(old) + local balance = normalize(old) + delta + applied = balance >= 0 + return if applied then { balance = balance } else nil + end) + end) + if not ok then + warn("Осколки: не удалось записать", userId, result) + return false + end + if applied and s and states[userId] == s then + s.balance = result.balance + publish(userId) + end + return applied + end + -- DataStore недоступен (Studio без доступа к API) — только в памяти. + if s and s.balance + delta >= 0 then + s.balance += delta + publish(userId) + return true + end + return false +end + +function Shards.Add(userId: number, amount: number): boolean + return amount > 0 and change(userId, math.floor(amount)) +end + +-- Списать за покупку. false — не хватает осколков или не удалось записать. +function Shards.Spend(player: Player, amount: number): boolean + local s = states[player.UserId] + if amount <= 0 or not s or s.balance < amount then + return false + end + return change(player.UserId, -math.floor(amount)) +end + +-- Осколки из кейса: { kind = "shards", amount = N } +Cases.Rewards.shards = function(player: Player, item) + Shards.Add(player.UserId, item.amount or 0) +end + +local function onPlayerAdded(player: Player) + local userId = player.UserId + local s = { balance = 0, loaded = false, canSave = false } + states[userId] = s + local ok, data = false, nil + if store then + ok, data = pcall(function() + return store:GetAsync("u" .. userId) + end) + end + if states[userId] ~= s then + return + end + s.balance = if ok then normalize(data) else Config.Shards.Start + s.canSave = ok + s.loaded = true + publish(userId) +end + +function Shards.Init() + Players.PlayerAdded:Connect(onPlayerAdded) + Players.PlayerRemoving:Connect(function(player) + states[player.UserId] = nil + end) + for _, player in Players:GetPlayers() do + task.spawn(onPlayerAdded, player) + end +end + +return Shards diff --git a/Zombi/src/server/Weapons.luau b/Zombi/src/server/Weapons.luau new file mode 100644 index 0000000..a618d35 --- /dev/null +++ b/Zombi/src/server/Weapons.luau @@ -0,0 +1,209 @@ +-- Пушки на турели: выстрелы считает сервер (темп, перегрев, сектор обстрела, урон), клиенты рисуют трассеры +-- и снаряды. Параметры — у пушки из слота «Оружие» (Config.Garage.Parts → gun): автоматы попадают сразу, +-- пушка и ракетница стреляют летящими снарядами со взрывом. +-- Бочки на карте взрываются от попаданий, взрыв поджигает соседние бочки. + +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage.Shared.Config) +local GunMath = require(ReplicatedStorage.Shared.GunMath) +local Buggy = require(script.Parent.Buggy) +local World = require(script.Parent.World) + +local G = Config.Gun +local Weapons = {} + +local Tracer: RemoteEvent +local rng = Random.new() + +local function humanoidOf(instance: Instance): Humanoid? + local model = instance:FindFirstAncestorOfClass("Model") + return model and model:FindFirstChildOfClass("Humanoid") +end + +local function explode(barrel: BasePart) + if not barrel.Parent then + return + end + local respawn = barrel:Clone() + local parent = barrel.Parent + local position = barrel.Position + barrel:Destroy() + + local explosion = Instance.new("Explosion") + explosion.Position = position + explosion.BlastRadius = G.ExplosionRadius + explosion.BlastPressure = 150000 -- подбрасывает багги, но не разваливает их + explosion.DestroyJointRadiusPercent = 0 + explosion.ExplosionType = Enum.ExplosionType.NoCraters -- свои воронки фиксированного размера (World.Crater) + World.Crater(position) + local damaged = {} + explosion.Hit:Connect(function(part, distance) + local humanoid = humanoidOf(part) + if humanoid and not damaged[humanoid] then + damaged[humanoid] = true + humanoid:TakeDamage(G.ExplosionDamage * math.clamp(1 - distance / G.ExplosionRadius, 0.2, 1)) + end + if part:GetAttribute("Explosive") then + task.delay(0.15, explode, part) -- цепная реакция + end + end) + explosion.Parent = workspace + + task.delay(G.BarrelRespawn, function() + respawn:SetAttribute("Health", G.BarrelHealth) + respawn.Parent = parent + end) +end + +-- Пуля попала в instance. +local function hit(instance: BasePart, shooter: Player, damage: number) + if instance:GetAttribute("Explosive") then + local health = (instance:GetAttribute("Health") or 1) - 1 + instance:SetAttribute("Health", health) + if health <= 0 then + explode(instance) + end + return + end + local humanoid = humanoidOf(instance) + if humanoid and humanoid.Parent ~= shooter.Character and humanoid.Health > 0 then + humanoid:SetAttribute("LastHitBy", shooter.UserId) -- кому награда за убитого зомби (Zombies) + humanoid:TakeDamage(damage) + return + end + -- Бронелист (детали из гаража с armor) держит пулю. + if instance:GetAttribute("Armor") then + return + end + -- Попали в чужую багги — достаётся водителю. + local model = instance:FindFirstAncestorOfClass("Model") + local driver = model and Buggy.Driver(model) + local driverHumanoid = driver and driver.Character and driver.Character:FindFirstChildOfClass("Humanoid") + if driverHumanoid and driver ~= shooter then + driverHumanoid:TakeDamage(damage * 0.5) + end +end + +-- Взрыв снаряда пушки или ракеты: урон спадает от центра к краю, бочки рядом детонируют. +-- Стрелка не задевает. Багги в радиусе подбрасывает, водителю достаётся половина (если не прикрыт бронёй целиком). +local function blast(position: Vector3, spec, shooter: Player) + local explosion = Instance.new("Explosion") + explosion.Position = position + explosion.BlastRadius = spec.blastRadius + explosion.BlastPressure = 90000 + explosion.DestroyJointRadiusPercent = 0 + explosion.ExplosionType = Enum.ExplosionType.NoCraters + World.Crater(position) + local damaged = {} + explosion.Hit:Connect(function(part, distance) + local falloff = math.clamp(1 - distance / spec.blastRadius, 0.2, 1) + if part:GetAttribute("Explosive") then + task.delay(0.1, explode, part) + return + end + local humanoid = humanoidOf(part) + if not humanoid then + local model = part:FindFirstAncestorOfClass("Model") + local driver = model and Buggy.Driver(model) + humanoid = driver and driver.Character and driver.Character:FindFirstChildOfClass("Humanoid") + falloff *= 0.5 + end + if humanoid and not damaged[humanoid] and humanoid.Parent ~= shooter.Character then + damaged[humanoid] = true + humanoid:SetAttribute("LastHitBy", shooter.UserId) + humanoid:TakeDamage(spec.damage * falloff) + end + end) + explosion.Parent = workspace +end + +local function aimTurret(data, yaw: number, pitch: number) + data.gun.motor.C0 = GunMath.Mount * GunMath.Rotation(yaw, pitch) +end + +local function isAngle(v): boolean + return typeof(v) == "number" and v == v and math.abs(v) < 4 +end + +function Weapons.Init(remotes: Folder) + local FireGun = Instance.new("RemoteEvent") + FireGun.Name = "FireGun" + FireGun.Parent = remotes + + local AimGun = Instance.new("UnreliableRemoteEvent") + AimGun.Name = "AimGun" + AimGun.Parent = remotes + + Tracer = Instance.new("RemoteEvent") + Tracer.Name = "Tracer" + Tracer.Parent = remotes + + -- Поворот турели, чтобы другие игроки видели, куда целится водитель. + AimGun.OnServerEvent:Connect(function(player, yaw, pitch) + local model = Buggy.FindDrivenBy(player) + if model and isAngle(yaw) and isAngle(pitch) then + aimTurret(Buggy.Get(model), + math.clamp(yaw, -math.rad(G.YawLimit), math.rad(G.YawLimit)), + math.clamp(pitch, math.rad(G.PitchMin), math.rad(G.PitchMax))) + end + end) + + FireGun.OnServerEvent:Connect(function(player, target) + if typeof(target) ~= "Vector3" then + return + end + local model = Buggy.FindDrivenBy(player) + if not model then + return + end + local data = Buggy.Get(model) + local gun = data.gun + local spec = gun.spec + local now = os.clock() + + -- Остывание и перегрев (темп с запасом 20% на сетевые задержки) + gun.heat = math.max(gun.heat - (now - gun.heatTime) * G.CoolRate, 0) + gun.heatTime = now + if gun.overheated and gun.heat <= G.CoolResume then + gun.overheated = false + end + if gun.overheated or now - gun.lastShot < 0.8 / spec.fireRate then + return + end + gun.lastShot = now + gun.heat += spec.heatPerShot + if gun.heat >= 1 then + gun.overheated = true + end + + local chassisCFrame = data.chassis.CFrame + local mount = (chassisCFrame * GunMath.Mount).Position + local yaw, pitch = GunMath.Angles(chassisCFrame, target - mount) + aimTurret(data, yaw, pitch) + + local spread = math.rad(spec.spread) + local turret = GunMath.Turret(chassisCFrame, yaw + rng:NextNumber(-spread, spread), pitch + rng:NextNumber(-spread, spread)) + local origin = (turret * GunMath.Muzzle).Position + local direction = turret.LookVector * G.Range + + local params = RaycastParams.new() + params.FilterType = Enum.RaycastFilterType.Exclude + params.FilterDescendantsInstances = { model, player.Character } + local result = workspace:Raycast(origin, direction, params) + local hitPosition = result and result.Position or origin + direction + + if spec.kind == "bullet" then + if result then + hit(result.Instance, player, spec.damage) + end + else + -- Снаряд летит до точки попадания (клиенты рисуют полёт), там взрыв. Промах — взрыв в конце дальности. + local travel = (hitPosition - origin).Magnitude / spec.speed + task.delay(travel, blast, hitPosition, spec, player) + end + Tracer:FireAllClients(model, origin, hitPosition, player.UserId) + end) +end + +return Weapons diff --git a/Zombi/src/server/World.luau b/Zombi/src/server/World.luau new file mode 100644 index 0000000..50986ff --- /dev/null +++ b/Zombi/src/server/World.luau @@ -0,0 +1,475 @@ +-- Пустошь: плавный рельеф из вокселей, дороги, руины, сгоревшие машины, бочки, трамплины, атмосфера. +-- Карт несколько: основная вокруг ангара и по одной на каждый круг лобби — у каждой команды своя, +-- со своим сидом. Карты команд стоят в ряд по X, далеко друг от друга. + +local Lighting = game:GetService("Lighting") +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage.Shared.Config) +local Hangar = require(script.Parent.Hangar) + +local W = Config.World +local World = {} + +local RES = 4 -- размер вокселя +local Y_MIN, Y_MAX = -12, 100 +local CHUNK = 128 + +-- Карта, которую сейчас строим: { origin, seed, rng }. Функции ниже работают в её локальных координатах. +type Map = { origin: Vector3, seed: number, rng: Random, ready: boolean } + +local function newMap(origin: Vector3, mapSeed: number): Map + return { origin = origin, seed = mapSeed * 0.001, rng = Random.new(mapSeed), ready = false } +end + +-- Основная пустошь вокруг ангара и карты команд (индекс совпадает с номером круга лобби). +local hub = newMap(Vector3.zero, W.Seed) +World.Arenas = {} :: { Map } +for i = 1, #Hangar.LobbySpots do + World.Arenas[i] = newMap(Vector3.new(i * Config.Lobby.MapSpacing, 0, 0), W.Seed + i * 101) +end + +local current: Map = hub +local rng = hub.rng +local seed = hub.seed + +local RUST = Color3.fromRGB(122, 72, 42) +local BURNT = Color3.fromRGB(45, 40, 36) +local CONCRETE = Color3.fromRGB(150, 145, 135) +local FOG = Color3.fromRGB(150, 150, 153) -- серый: цвет атмосферы, завесы за краем и туманного потолка + +local function onRoad(x: number, z: number): boolean + return math.abs(x) < W.RoadHalfWidth or math.abs(z) < W.RoadHalfWidth +end + +-- Высота земли в точке (координаты от центра карты) для карты с сидом mapSeed. В центре — ровная площадка. +local function heightWith(mapSeed: number, x: number, z: number): number + local h = W.BaseHeight + + math.noise(x / 230, z / 230, mapSeed) * 50 + + math.noise(x / 70, z / 70, mapSeed + 10) * 10 + -- Дороги сглаживаем, чтобы по ним было приятно гонять. + if onRoad(x, z) then + h = W.BaseHeight + (h - W.BaseHeight) * 0.35 + end + h = math.max(h, 2) + local d = math.sqrt(x * x + z * z) + if d < W.SpawnFlatRadius then + local t = math.clamp((d - W.SpawnFlatRadius * 0.6) / (W.SpawnFlatRadius * 0.4), 0, 1) + h = W.BaseHeight + (h - W.BaseHeight) * t + end + return h +end + +-- Высота для карты, которую сейчас строим. +local function height(x: number, z: number): number + return heightWith(seed, x, z) +end + +-- Исходная высота земли в мировой точке (как её построили), или nil — точка не на карте. +function World.GroundHeight(x: number, z: number): number? + local half = W.Size / 2 + for _, map in { hub, table.unpack(World.Arenas) } do + local lx, lz = x - map.origin.X, z - map.origin.Z + if math.abs(lx) < half and math.abs(lz) < half then + return heightWith(map.seed, lx, lz) + end + end + return nil +end + +-- Воронка от взрыва: всегда одного размера и отсчитывается от исходной высоты земли, а не от текущей, +-- поэтому повторные взрывы в одном месте её не углубляют. Под воронкой досыпаем грунт до низа рельефа — +-- провалиться под карту нельзя. Взрыв высоко над землёй воронку не оставляет. +function World.Crater(position: Vector3) + local ground = World.GroundHeight(position.X, position.Z) + if not ground or position.Y > ground + W.CraterRadius * 1.5 then + return + end + local r = W.CraterRadius + local center = Vector3.new(position.X, ground - W.CraterDepth + r, position.Z) + local terrain = workspace.Terrain + terrain:FillBall(center, r, Enum.Material.Air) + -- Дно: цилиндр грунта от низа рельефа до уровня чуть ниже самой низкой исходной точки вокруг — + -- на склоне он не вылезет бугром наружу. + local lowest = ground + for i = 0, 7 do + local a = i / 8 * math.pi * 2 + local h = World.GroundHeight(position.X + math.cos(a) * (r + 1), position.Z + math.sin(a) * (r + 1)) + lowest = math.min(lowest, h or ground) + end + local floor = math.min(lowest, ground) - W.CraterDepth + if floor > Y_MIN + 1 then + terrain:FillCylinder(CFrame.new(position.X, (Y_MIN + floor) / 2, position.Z), floor - Y_MIN, r + 1, Enum.Material.Ground) + end +end + +local function materialAt(x: number, z: number, h: number): Enum.Material + if onRoad(x, z) then + return Enum.Material.Asphalt + elseif h > 38 then + return Enum.Material.Rock + elseif h > 22 or math.noise(x / 40, z / 40, seed + 20) > 0.25 then + return Enum.Material.Ground + end + return Enum.Material.Sand +end + +local function writeChunk(x0: number, z0: number) + local o = current.origin + local region = Region3.new(Vector3.new(o.X + x0, Y_MIN, o.Z + z0), Vector3.new(o.X + x0 + CHUNK, Y_MAX, o.Z + z0 + CHUNK)) + local nx, ny, nz = CHUNK // RES, (Y_MAX - Y_MIN) // RES, CHUNK // RES + local materials, occupancy = {}, {} + for ix = 1, nx do + local matX, occX = {}, {} + for iy = 1, ny do + matX[iy], occX[iy] = {}, {} + end + for iz = 1, nz do + local wx = x0 + (ix - 0.5) * RES + local wz = z0 + (iz - 0.5) * RES + local h = height(wx, wz) + local mat = materialAt(wx, wz, h) + for iy = 1, ny do + local occ = math.clamp((h - (Y_MIN + (iy - 1) * RES)) / RES, 0, 1) + matX[iy][iz] = if occ > 0 then mat else Enum.Material.Air + occX[iy][iz] = occ + end + end + materials[ix], occupancy[ix] = matX, occX + end + workspace.Terrain:WriteVoxels(region, RES, materials, occupancy) +end + +local function buildTerrain() + local half = W.Size / 2 + for x0 = -half, half - CHUNK, CHUNK do + for z0 = -half, half - CHUNK, CHUNK do + writeChunk(x0, z0) + task.wait() -- не подвешиваем сервер + end + end +end + +-- ===== Объекты ===== + +local props: Folder + +local function part(props_, className: string?): BasePart + local p = Instance.new(className or "Part") + p.Anchored = true + p.TopSurface = Enum.SurfaceType.Smooth + p.BottomSurface = Enum.SurfaceType.Smooth + for k, v in props_ do + p[k] = v + end + p.Parent = p.Parent or props + return p +end + +-- Случайная точка на пустоши: подальше от центра и (по желанию) от дорог. Возвращает мировые координаты. +local function randomSpot(avoidRoads: boolean): (number, number, number) + local half = W.Size / 2 - 20 + local o = current.origin + for _ = 1, 50 do + local x = rng:NextNumber(-half, half) + local z = rng:NextNumber(-half, half) + local far = math.sqrt(x * x + z * z) > W.SpawnFlatRadius + 10 + if far and not (avoidRoads and math.abs(x) < W.RoadHalfWidth + 6 or avoidRoads and math.abs(z) < W.RoadHalfWidth + 6) then + return o.X + x, height(x, z), o.Z + z + end + end + return o.X + half, height(half, half), o.Z + half +end + +local function yaw(): CFrame + return CFrame.Angles(0, rng:NextNumber(0, math.pi * 2), 0) +end + +local function ruin(x: number, h: number, z: number) + local base = CFrame.new(x, h, z) * yaw() + for i = 1, rng:NextInteger(3, 6) do + local height = rng:NextNumber(5, 16) + local length = rng:NextNumber(8, 20) + local offset = CFrame.new(rng:NextNumber(-14, 14), height / 2 - 1, rng:NextNumber(-14, 14)) + local tilt = CFrame.Angles(rng:NextNumber(-0.15, 0.15), (i % 2) * math.pi / 2, rng:NextNumber(-0.1, 0.1)) + part({ Size = Vector3.new(length, height, 1.6), CFrame = base * offset * tilt, Color = CONCRETE, Material = Enum.Material.Concrete }) + end + for _ = 1, rng:NextInteger(4, 9) do + local s = rng:NextNumber(1.5, 4) + part({ + Size = Vector3.new(s, s * 0.6, s), + CFrame = base * CFrame.new(rng:NextNumber(-16, 16), s * 0.2, rng:NextNumber(-16, 16)) * CFrame.Angles(rng:NextNumber(-0.5, 0.5), rng:NextNumber(0, 3), 0), + Color = CONCRETE:Lerp(BURNT, rng:NextNumber(0, 0.5)), + Material = Enum.Material.Concrete, + }) + end +end + +local function wreck(x: number, h: number, z: number) + local flipped = rng:NextNumber() < 0.25 + local base = CFrame.new(x, h + 1.4, z) * yaw() * CFrame.Angles(flipped and math.pi or rng:NextNumber(-0.1, 0.1), 0, rng:NextNumber(-0.15, 0.15)) + local color = RUST:Lerp(BURNT, rng:NextNumber(0.2, 0.9)) + part({ Size = Vector3.new(6, 2.2, 12), CFrame = base, Color = color, Material = Enum.Material.CorrodedMetal }) + part({ Size = Vector3.new(5.4, 2, 5.5), CFrame = base * CFrame.new(0, 2, 0.5), Color = BURNT, Material = Enum.Material.CorrodedMetal }) + for _, wx in { -3, 3 } do + for _, wz in { -4, 4 } do + if rng:NextNumber() < 0.7 then + part({ + Shape = Enum.PartType.Cylinder, + Size = Vector3.new(1, 2.6, 2.6), + CFrame = base * CFrame.new(wx, -1.1, wz), + Color = Color3.fromRGB(25, 25, 25), + Material = Enum.Material.Fabric, + }) + end + end + end + if rng:NextNumber() < 0.15 then + local fire = Instance.new("Fire") + fire.Size = 8 + fire.Heat = 12 + fire.Parent = part({ Size = Vector3.new(1, 1, 1), CFrame = base * CFrame.new(0, 2, -4), Transparency = 1, CanCollide = false }) + end +end + +local function barrels(x: number, h: number, z: number) + local base = CFrame.new(x, h, z) + for i = 1, rng:NextInteger(3, 6) do + local barrel = part({ + Shape = Enum.PartType.Cylinder, + Size = Vector3.new(3, 2.2, 2.2), + CFrame = base * CFrame.new(rng:NextNumber(-4, 4), 1.4, rng:NextNumber(-4, 4)) * CFrame.Angles(0, 0, math.pi / 2), + Color = (i % 2 == 0 and Color3.fromRGB(160, 50, 30) or Color3.fromRGB(190, 110, 30)):Lerp(RUST, 0.4), + Material = Enum.Material.CorrodedMetal, + }) + -- Бочки взрываются от пулемёта (см. Weapons). + barrel.Name = "ExplosiveBarrel" + barrel:SetAttribute("Explosive", true) + barrel:SetAttribute("Health", Config.Gun.BarrelHealth) + if i == 1 and rng:NextNumber() < 0.5 then + local fire = Instance.new("Fire") + fire.Size = 4 + fire.Parent = barrel + local light = Instance.new("PointLight") + light.Color = Color3.fromRGB(255, 140, 50) + light.Range = 18 + light.Brightness = 2 + light.Parent = barrel + end + end +end + +local function deadTree(x: number, h: number, z: number) + local height = rng:NextNumber(10, 22) + local color = Color3.fromRGB(70, 55, 42) + local trunk = CFrame.new(x, h + height / 2 - 0.5, z) * CFrame.Angles(rng:NextNumber(-0.1, 0.1), 0, rng:NextNumber(-0.1, 0.1)) + part({ Shape = Enum.PartType.Cylinder, Size = Vector3.new(height, 1.4, 1.4), CFrame = trunk * CFrame.Angles(0, 0, math.pi / 2), Color = color, Material = Enum.Material.Wood }) + for _ = 1, rng:NextInteger(2, 4) do + local length = rng:NextNumber(4, 8) + local at = trunk * CFrame.new(0, rng:NextNumber(0, height / 2), 0) * yaw() * CFrame.Angles(0, 0, rng:NextNumber(0.6, 1.1)) + part({ + Shape = Enum.PartType.Cylinder, + Size = Vector3.new(length, 0.6, 0.6), + CFrame = at * CFrame.new(length / 2, 0, 0), + Color = color, + Material = Enum.Material.Wood, + }) + end +end + +local function ramp(x: number, z: number, alongZ: boolean) + local h = height(x, z) + local turn = (alongZ and 0 or math.pi / 2) + (rng:NextNumber() < 0.5 and math.pi or 0) + part({ + Name = "Ramp", + Size = Vector3.new(12, 5, 22), + CFrame = CFrame.new(current.origin + Vector3.new(x, h + 2.2, z)) * CFrame.Angles(0, turn, 0), + Color = RUST, + Material = Enum.Material.CorrodedMetal, + }, "WedgePart") +end + +local function buildProps(name: string) + props = Instance.new("Folder") + props.Name = name + props.Parent = workspace + + for _ = 1, 26 do + ruin(randomSpot(true)) + end + for _ = 1, 40 do + wreck(randomSpot(false)) + end + for _ = 1, 30 do + barrels(randomSpot(true)) + end + for _ = 1, 45 do + deadTree(randomSpot(true)) + end + -- Трамплины на дорогах + local half = W.Size / 2 + for d = W.SpawnFlatRadius + 40, half - 40, 90 do + for _, sign in { -1, 1 } do + ramp(rng:NextNumber(-4, 4), d * sign, true) + ramp(d * sign, rng:NextNumber(-4, 4), false) + end + end +end + +local function setupLighting() + for _, child in Lighting:GetChildren() do + if child:IsA("Atmosphere") or child:IsA("PostEffect") or child:IsA("Sky") then + child:Destroy() + end + end + -- Мягкий закатный свет без пересветов: умеренное солнце, тёмный ambient (тени не серые), + -- чуть сниженная экспозиция и слабые отражения — металл и фольга не слепят. + Lighting.ClockTime = 17.4 + Lighting.Brightness = 1.4 + Lighting.ExposureCompensation = -0.25 + Lighting.Ambient = Color3.fromRGB(42, 36, 32) + Lighting.OutdoorAmbient = Color3.fromRGB(100, 86, 72) + Lighting.EnvironmentDiffuseScale = 0.5 + Lighting.EnvironmentSpecularScale = 0.35 + Lighting.GlobalShadows = true + + -- Лёгкая дымка на карте. У края её сгущает клиент (EdgeFog), за краем стоит завеса (buildEdge). + local atmosphere = Instance.new("Atmosphere") + atmosphere.Density = 0.26 + atmosphere.Offset = 0.1 + atmosphere.Color = FOG + atmosphere.Decay = Color3.fromRGB(105, 105, 108) + atmosphere.Glare = 0.1 + atmosphere.Haze = 1 + atmosphere.Parent = Lighting + + local grade = Instance.new("ColorCorrectionEffect") + grade.Brightness = -0.02 + grade.Saturation = -0.15 + grade.Contrast = 0.06 + grade.TintColor = Color3.fromRGB(255, 238, 220) + grade.Parent = Lighting + + -- Свечение только у по-настоящему ярких деталей (неон, лампы), а не у всего освещённого. + local bloom = Instance.new("BloomEffect") + bloom.Intensity = 0.25 + bloom.Size = 16 + bloom.Threshold = 2 + bloom.Parent = Lighting + + local rays = Instance.new("SunRaysEffect") + rays.Intensity = 0.03 + rays.Spread = 0.6 + rays.Parent = Lighting +end + +local EDGE_SKIRT = 384 -- полоса ровного песка за краем: в тумане виден горизонт, а не пустота +local BORDER_H = 400 +-- Туман за краем и сверху: слои полупрозрачных «простыней» серого цвета. Каждый слой наполовину прозрачен, +-- вместе почти непрозрачны — за краем и над картой не видно ничего даже издалека. +-- Сбоку — завеса по периметру от земли до потолка, сверху — туманный потолок на высоте W.FogCeiling. +local CURTAIN_LAYERS = { 6, 22, 38, 54, 70, 86 } -- отступ слоя завесы от края карты, studs +local CEILING_LAYERS = { 0, 12, 24, 36, 48 } -- высота слоя потолка над W.FogCeiling +local SHEET_ALPHA = 0.5 -- прозрачность одного слоя + +local function fogSheet(cf: CFrame, size: Vector3, face: Enum.NormalId) + local sheet = part({ Name = "Fog", Size = size, CFrame = cf, Transparency = 1, CanCollide = false, CanQuery = false, CanTouch = false, CastShadow = false }) + local gui = Instance.new("SurfaceGui") + gui.Face = face + gui.SizingMode = Enum.SurfaceGuiSizingMode.PixelsPerStud + gui.PixelsPerStud = 0.5 + gui.LightInfluence = 0 -- ровный цвет без теней, как у дымки + gui.MaxDistance = 0 -- видно с любого расстояния + gui.Parent = sheet + local fog = Instance.new("Frame") + fog.Size = UDim2.fromScale(1, 1) + fog.BackgroundColor3 = FOG + fog.BackgroundTransparency = SHEET_ALPHA + fog.BorderSizePixel = 0 + fog.Parent = gui +end + +-- Край карты: невидимые стены (не выехать, пули сквозь них летят) и песок за ними. +local function buildEdge() + local o = current.origin + local half = W.Size / 2 + local outer = half + EDGE_SKIRT + local strips = { + { Vector3.new(0, 0, -(half + EDGE_SKIRT / 2)), Vector3.new(outer * 2, 0, EDGE_SKIRT) }, + { Vector3.new(0, 0, half + EDGE_SKIRT / 2), Vector3.new(outer * 2, 0, EDGE_SKIRT) }, + { Vector3.new(-(half + EDGE_SKIRT / 2), 0, 0), Vector3.new(EDGE_SKIRT, 0, half * 2) }, + { Vector3.new(half + EDGE_SKIRT / 2, 0, 0), Vector3.new(EDGE_SKIRT, 0, half * 2) }, + } + for _, strip in strips do + workspace.Terrain:FillBlock(CFrame.new(o + strip[1] + Vector3.new(0, W.BaseHeight - 6, 0)), strip[2] + Vector3.new(0, 12, 0), Enum.Material.Sand) + end + for _, side in { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } } do + local alongX = side[1] == 0 + part({ + Name = "MapBorder", + Size = if alongX then Vector3.new(W.Size + 8, BORDER_H, 4) else Vector3.new(4, BORDER_H, W.Size + 8), + CFrame = CFrame.new(o + Vector3.new(side[1] * (half + 2), BORDER_H / 2 - 20, side[2] * (half + 2))), + Transparency = 1, + CanQuery = false, + CastShadow = false, + }) + end + + -- Завеса: у каждой стороны слои лицом к центру карты, от земли до верхнего слоя потолка. + local length = W.Size + 2 * (CURTAIN_LAYERS[#CURTAIN_LAYERS] + 20) + local bottom, top = -20, W.FogCeiling + CEILING_LAYERS[#CEILING_LAYERS] + 4 + local height, y = top - bottom, (top + bottom) / 2 + for _, offset in CURTAIN_LAYERS do + local d = half + offset + fogSheet(CFrame.new(o + Vector3.new(d, y, 0)), Vector3.new(0.2, height, length), Enum.NormalId.Left) + fogSheet(CFrame.new(o + Vector3.new(-d, y, 0)), Vector3.new(0.2, height, length), Enum.NormalId.Right) + fogSheet(CFrame.new(o + Vector3.new(0, y, d)), Vector3.new(length, height, 0.2), Enum.NormalId.Front) + fogSheet(CFrame.new(o + Vector3.new(0, y, -d)), Vector3.new(length, height, 0.2), Enum.NormalId.Back) + end + -- Потолок: слои лицом вниз, над всей картой и завесой. + for _, lift in CEILING_LAYERS do + fogSheet(CFrame.new(o + Vector3.new(0, W.FogCeiling + lift, 0)), Vector3.new(length, 0.2, length), Enum.NormalId.Bottom) + end +end + +local function buildMap(map: Map, name: string) + current, rng, seed = map, map.rng, map.seed + buildTerrain() + buildProps(name) + buildEdge() + map.ready = true +end + +-- Куда поставить багги k-го из n игроков команды: по кругу в центре карты, мордой наружу. +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) +end + +function World.ArenaReady(index: number): boolean + local map = World.Arenas[index] + return map ~= nil and map.ready +end + +-- Свет и ангар — сразу: игроки появляются в ангаре, пока строится рельеф. +function World.BuildHangar() + setupLighting() + Hangar.Build() +end + +-- Рельеф и объекты: сначала пустошь вокруг ангара, потом карты команд. Несколько секунд на каждую. +function World.BuildMaps() + workspace.Terrain:Clear() + buildMap(hub, "Wasteland") + -- Под ангаром срезаем рельеф ниже пола: гладкий воксельный песок иначе проступает сквозь бетон. + local floor = Hangar.FloorSize + workspace.Terrain:FillBlock(CFrame.new(0, Hangar.FloorY + 4, 0), Vector3.new(floor.X, 11, floor.Z), Enum.Material.Air) + for i, map in World.Arenas do + buildMap(map, "TeamMap" .. i) + end +end + +return World diff --git a/Zombi/src/server/Zombies.luau b/Zombi/src/server/Zombies.luau new file mode 100644 index 0000000..d7aac76 --- /dev/null +++ b/Zombi/src/server/Zombies.luau @@ -0,0 +1,330 @@ +-- Зомби на картах команд. Когда команда выехала (Lobby → Zombies.Start), на карте держится стая: +-- новые приходят из-за пределов видимости вокруг игроков, бегут к ближайшему и бьют вблизи. +-- Урон им наносят пули и взрывы (Weapons) и таран багги (здесь). Каждое попадание сервер сообщает клиентам +-- (ZombieHit) — они рисуют вылетающие цифры урона и искры. Убившему — осколки. +-- Команда покинула карту (Lobby → Zombies.Stop) — зомби убираются. + +local Debris = game:GetService("Debris") +local Players = game:GetService("Players") +local ReplicatedStorage = game:GetService("ReplicatedStorage") + +local Config = require(ReplicatedStorage.Shared.Config) +local Buggy = require(script.Parent.Buggy) +local Shards = require(script.Parent.Shards) +local World = require(script.Parent.World) + +local Z = Config.Zombies +local Zombies = {} + +local WALK_ANIMATION = "rbxassetid://180426354" -- стандартная анимация ходьбы R6 от Roblox +local THINK_INTERVAL = 0.25 +-- Детали спереди багги усиливают таран +local FRONT_BONUS = { spikes = 1.4, ram = 1.3, bucket = 1.2, bayonets = 1.8 } + +local rng = Random.new() +local template: Model? = nil +-- [номер карты] = { index, folder, zombies = { [Model] = data }, started } +local arenas = {} +local HitRemote: RemoteEvent + +-- ===== Модель ===== + +local function makeTemplate(): Model? + local ok, model = pcall(function() + local description = Instance.new("HumanoidDescription") + description.HeadColor = Z.Color + description.LeftArmColor = Z.Color + description.RightArmColor = Z.Color + description.TorsoColor = Color3.fromRGB(72, 62, 50) -- рваная рубаха + description.LeftLegColor = Color3.fromRGB(55, 52, 64) + description.RightLegColor = Color3.fromRGB(55, 52, 64) + return Players:CreateHumanoidModelFromDescription(description, Enum.HumanoidRigType.R6) + end) + if not ok or not model then + warn("Зомби: не удалось собрать модель", model) + return nil + end + model.Name = "Zombie" + model:SetAttribute("Zombie", true) + for _, d in model:GetDescendants() do + if d:IsA("BaseScript") then + d:Destroy() -- стандартная анимация игрока не нужна + end + end + local humanoid = model:FindFirstChildOfClass("Humanoid") :: Humanoid + humanoid.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None + humanoid.HealthDisplayType = Enum.HumanoidHealthDisplayType.AlwaysOff + humanoid.MaxHealth = Z.Health + humanoid.Health = Z.Health + humanoid.BreakJointsOnDeath = true + if not humanoid:FindFirstChildOfClass("Animator") then + Instance.new("Animator", humanoid) + end + + -- Светящиеся красные глаза + local head = model:FindFirstChild("Head") :: BasePart? + if head then + for _, x in { -0.2, 0.2 } do + local eye = Instance.new("Part") + eye.Name = "Eye" + eye.Size = Vector3.new(0.2, 0.12, 0.05) + eye.CFrame = head.CFrame * CFrame.new(x, 0.15, -head.Size.Z / 2 - 0.02) + eye.Color = Color3.fromRGB(255, 40, 30) + eye.Material = Enum.Material.Neon + eye.CanCollide = false + eye.CanQuery = false + eye.Massless = true + eye.Parent = model + local weld = Instance.new("WeldConstraint") + weld.Part0 = head + weld.Part1 = eye + weld.Parent = eye + end + end + -- Руки вытянуты вперёд — анимация ходьбы раскачивает их уже от этого положения. + 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 + joint.C0 *= CFrame.Angles(0, 0, sign * math.pi / 2) + end + end + return model +end + +-- ===== Игроки на карте ===== + +local function playersIn(index: number) + local list = {} + for _, player in Players:GetPlayers() do + local character = player.Character + local humanoid = character and character:FindFirstChildOfClass("Humanoid") + local root = character and character:FindFirstChild("HumanoidRootPart") :: BasePart? + if player:GetAttribute("Arena") == index and humanoid and root and humanoid.Health > 0 then + table.insert(list, { player = player, humanoid = humanoid, root = root }) + end + end + return list +end + +-- Точка появления: на земле, на расстоянии от случайного игрока, внутри карты. +local function spawnPoint(index: number, targets): Vector3? + if #targets == 0 then + return nil + end + local map = World.Arenas[index] + local limit = Config.World.Size / 2 - 30 + for _ = 1, 12 do + local around = targets[rng:NextInteger(1, #targets)].root.Position + local angle = rng:NextNumber(0, math.pi * 2) + local distance = rng:NextNumber(Z.SpawnDistance[1], Z.SpawnDistance[2]) + local x, z = around.X + math.cos(angle) * distance, around.Z + math.sin(angle) * distance + if math.abs(x - map.origin.X) < limit and math.abs(z - map.origin.Z) < limit then + local ground = World.GroundHeight(x, z) + if ground then + return Vector3.new(x, ground + 3.5, z) + end + end + end + return nil +end + +-- ===== Урон и смерть ===== + +local function onDeath(arena, model: Model, data) + arena.zombies[model] = nil + local killerId = data.humanoid:GetAttribute("LastHitBy") + local killer = killerId and Players:GetPlayerByUserId(killerId) + if killer and Z.ShardsPerKill > 0 then + task.spawn(Shards.Add, killer.UserId, Z.ShardsPerKill) + end + -- Тело разлетается и через пару секунд исчезает. + for _, part in model:GetChildren() do + if part:IsA("BasePart") then + part.AssemblyLinearVelocity += Vector3.new(rng:NextNumber(-12, 12), rng:NextNumber(10, 22), rng:NextNumber(-12, 12)) + end + end + 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 + local now = os.clock() + local speed = (buggy.chassis.AssemblyLinearVelocity - data.root.AssemblyLinearVelocity).Magnitude + if speed < Z.RamSpeed or now - data.lastRam < 0.4 then + return + end + data.lastRam = now + local driver = Buggy.Driver(buggyModel) + if driver then + data.humanoid:SetAttribute("LastHitBy", driver.UserId) + 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) +end + +local function spawnZombie(arena, targets) + local at = spawnPoint(arena.index, targets) + if not at or not template then + return + end + local model = template:Clone() + model:PivotTo(CFrame.new(at) * CFrame.Angles(0, rng:NextNumber(0, math.pi * 2), 0)) + local humanoid = model:FindFirstChildOfClass("Humanoid") :: Humanoid + local root = model:FindFirstChild("HumanoidRootPart") :: BasePart + humanoid.WalkSpeed = rng:NextNumber(Z.WalkSpeed[1], Z.WalkSpeed[2]) + model.Parent = arena.folder + pcall(function() + root:SetNetworkOwner(nil) -- ИИ на сервере: физику зомби считает он же + end) + + local data = { humanoid = humanoid, root = root, speed = humanoid.WalkSpeed, lastAttack = 0, lastRam = 0, health = humanoid.Health, walk = nil } + local animator = humanoid:FindFirstChildOfClass("Animator") + if animator then + local animation = Instance.new("Animation") + animation.AnimationId = WALK_ANIMATION + local ok, track = pcall(function() + return animator:LoadAnimation(animation) + end) + if ok then + track.Looped = true + data.walk = track + end + end + arena.zombies[model] = data + + -- Каждое снижение здоровья — клиентам: цифры урона и искры над зомби. + humanoid.HealthChanged:Connect(function(health) + local lost = data.health - health + data.health = health + if lost >= 0.5 then + local head = model:FindFirstChild("Head") :: BasePart? + local position = if head then head.Position else root.Position + HitRemote:FireAllClients(position, math.floor(lost + 0.5), health <= 0) + end + end) + 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 + +-- ===== ИИ ===== + +local function think(arena) + local targets = playersIn(arena.index) + local now = os.clock() + local alive = 0 + for model, data in arena.zombies do + if data.humanoid.Health <= 0 then + continue + end + alive += 1 + -- Провалился или отстал далеко от всех — убираем, на его место придёт новый поближе. + if data.root.Position.Y < -40 then + arena.zombies[model] = nil + model:Destroy() + continue + end + local nearest, distance = nil, math.huge + for _, target in targets do + local d = (target.root.Position - data.root.Position).Magnitude + if d < distance then + nearest, distance = target, d + end + end + if nearest and distance > 450 then + arena.zombies[model] = nil + model:Destroy() + continue + end + if nearest then + -- Вне видимости бредут медленнее, заметив — бегут. + data.humanoid.WalkSpeed = data.speed * (if distance <= Z.SightRange then 1 else 0.6) + data.humanoid:MoveTo(nearest.root.Position) + if data.walk then + if not data.walk.IsPlaying then + data.walk:Play() + end + data.walk:AdjustSpeed(data.humanoid.WalkSpeed / 14) + end + if distance <= Z.AttackRange and now - data.lastAttack >= Z.AttackCooldown then + data.lastAttack = now + nearest.humanoid:TakeDamage(Z.AttackDamage) + end + elseif data.walk and data.walk.IsPlaying then + data.walk:Stop() + end + end + + -- Пополняем стаю до нужного размера (не больше двух за раз — чтобы не появлялись толпой). + if arena.started and #targets > 0 then + local wanted = math.min(Z.Max, Z.Base + Z.PerPlayer * #targets) + for _ = 1, math.min(2, wanted - alive - arena.pending) do + arena.pending += 1 + task.delay(if alive == 0 then 0 else Z.RespawnDelay * rng:NextNumber(0.3, 1), function() + arena.pending -= 1 + if arenas[arena.index] == arena then + spawnZombie(arena, playersIn(arena.index)) + end + end) + end + end +end + +-- ===== Карты ===== + +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) +end + +function Zombies.Stop(index: number) + local arena = arenas[index] + if arena then + arenas[index] = nil + arena.folder:Destroy() + end +end + +function Zombies.Init(remotes: Folder) + HitRemote = Instance.new("RemoteEvent") + HitRemote.Name = "ZombieHit" + HitRemote.Parent = remotes + task.spawn(function() + template = makeTemplate() + end) + task.spawn(function() + while true do + task.wait(THINK_INTERVAL) + for _, arena in arenas do + think(arena) + end + end + end) +end + +return Zombies diff --git a/Zombi/src/shared/BuggyStats.luau b/Zombi/src/shared/BuggyStats.luau new file mode 100644 index 0000000..058a504 --- /dev/null +++ b/Zombi/src/shared/BuggyStats.luau @@ -0,0 +1,39 @@ +-- Характеристики багги по набору деталей: одна и та же математика на сервере (скорость) и в меню гаража. +-- setup — { front, wheels, rear, armor, weapon } с id деталей из Config.Garage.Parts ("" — слот пуст). + +local Config = require(script.Parent.Config) + +local BuggyStats = {} + +local function eachPart(setup, fn: (any) -> ()) + for _, slot in Config.Garage.Slots do + local item = Config.PartById[setup[slot.id] or ""] + if item then + fn(item) + end + end +end + +-- Во сколько раз меняется максимальная скорость от установленных деталей. +function BuggyStats.SpeedFactor(setup): number + local factor = 1 + eachPart(setup, function(item) + factor *= item.speed or 1 + end) + return factor +end + +-- { speed = км/ч, [id характеристики] = 0..100 } для Config.Garage.Stats. +function BuggyStats.Compute(setup) + local result = { speed = Config.Buggy.MaxSpeed * BuggyStats.SpeedFactor(setup) } + for _, stat in Config.Garage.Stats do + local value = stat.base + eachPart(setup, function(item) + value += item.stats and item.stats[stat.id] or 0 + end) + result[stat.id] = math.clamp(value, 0, 100) + end + return result +end + +return BuggyStats diff --git a/Zombi/src/shared/Config.luau b/Zombi/src/shared/Config.luau new file mode 100644 index 0000000..87f3493 --- /dev/null +++ b/Zombi/src/shared/Config.luau @@ -0,0 +1,216 @@ +-- Настройки багги и карты. + +local Config = {} + +Config.Buggy = { + MaxSpeed = 50, -- studs/с вперёд (≈ км/ч) + ReverseSpeed = 20, + CreepSpeed = 12, -- ход без газа, когда зажат только поворот (A/D) + ThrottleRise = 0.8, -- за сколько секунд газ доходит до полного + ThrottleFall = 0.4, -- за сколько секунд газ сбрасывается + MotorTorque = 9000, -- тяга на каждое колесо (полный привод) + CoastTorque = 1500, -- торможение двигателем, когда газ отпущен + SteerAngle = 30, -- градусы на малой скорости + HighSpeedSteer = 0.4, -- на максимальной скорости руль поворачивается только на эту долю + SteerSpeed = 3, -- скорость поворота руля, рад/с + -- Размер колёс — у деталей слота «wheels» в Config.Garage.Parts (ставятся в гараже). + SuspensionTravel = 1, -- ход подвески вниз, studs + SpringStiffness = 6000, + SpringDamping = 300, + -- Если на W багги едет назад или руль перепутан — поменяйте знак на -1. + DriveSign = 1, + SteerSign = 1, + AutoFlipTime = 5, -- через столько секунд на боку или на крыше багги сама встаёт на колёса + AutoFlipTilt = 0.35, -- «перевёрнута», если верх рамы смотрит вверх меньше чем на столько (косинус наклона) +} + +-- Общее для всех пушек на турели. Темп, урон, разброс и нагрев — у каждой своё (слот «Оружие» в Config.Garage.Parts). +Config.Gun = { + Range = 400, + CoolRate = 0.4, -- остывание в секунду + CoolResume = 0.3, -- после перегрева можно стрелять, когда остынет до этого уровня + YawLimit = 75, -- насколько турель поворачивается влево/вправо, градусы + PitchMin = -12, + PitchMax = 30, + BarrelHealth = 3, -- попаданий до взрыва бочки + ExplosionRadius = 16, + ExplosionDamage = 50, + BarrelRespawn = 60, +} + +Config.World = { + Size = 1024, -- сторона карты, studs (кратно 128) + Seed = 1337, + BaseHeight = 8, -- высота земли в центре + SpawnFlatRadius = 130, -- ровная площадка вокруг ангара (полностью ровно до 60% радиуса) + RoadHalfWidth = 12, -- две дороги крест-накрест через центр + FogCeiling = 160, -- высота туманного потолка над картами (выше самых высоких холмов) + CraterRadius = 4, -- воронка от взрыва: радиус, studs (одинаковая для всех взрывов) + CraterDepth = 2, -- и глубина от исходной поверхности — повторные взрывы глубже не роют + CameraMaxZoom = 40, -- насколько далеко можно отдалить камеру от персонажа +} + +-- Тюнинг в личном гараже. Номера покрасок сохраняются в DataStore — новые добавляйте в конец. +Config.Garage = { + Paints = { + { name = "Ржавчина", color = Color3.fromRGB(128, 74, 40), material = Enum.Material.CorrodedMetal }, + { name = "Песок", color = Color3.fromRGB(194, 160, 110) }, + { name = "Хаки", color = Color3.fromRGB(92, 100, 60) }, + { name = "Красный", color = Color3.fromRGB(150, 35, 28) }, + { name = "Оранжевый", color = Color3.fromRGB(215, 110, 30) }, + { name = "Жёлтый", color = Color3.fromRGB(220, 175, 40) }, + { name = "Синий", color = Color3.fromRGB(45, 75, 125) }, + { name = "Чёрный", color = Color3.fromRGB(30, 30, 32) }, + { name = "Белый", color = Color3.fromRGB(215, 210, 200) }, + -- Редкие (rare) — закрыты: выигрываются на колесе фортуны или покупаются за осколки (price). + { name = "Хром", color = Color3.fromRGB(210, 212, 220), material = Enum.Material.Foil, rare = true, price = 400 }, + { name = "Золото", color = Color3.fromRGB(230, 180, 60), material = Enum.Material.Foil, rare = true, price = 600 }, + { name = "Кислота", color = Color3.fromRGB(120, 255, 60), material = Enum.Material.Neon, rare = true, price = 500 }, + { name = "Лава", color = Color3.fromRGB(255, 90, 30), material = Enum.Material.CrackedLava, rare = true, price = 500 }, + { name = "Лёд", color = Color3.fromRGB(150, 210, 240), material = Enum.Material.Glacier, rare = true, price = 400 }, + { name = "Карбон", color = Color3.fromRGB(28, 28, 32), material = Enum.Material.Slate, rare = true, price = 400 }, + }, + Accents = { -- каркас и диски + { name = "Тёмный металл", color = Color3.fromRGB(38, 36, 34) }, + { name = "Сталь", color = Color3.fromRGB(150, 150, 155) }, + { name = "Ржавчина", color = Color3.fromRGB(128, 74, 40), material = Enum.Material.CorrodedMetal }, + { name = "Красный", color = Color3.fromRGB(170, 40, 30) }, + { name = "Жёлтый", color = Color3.fromRGB(230, 185, 40) }, + { name = "Кислотный", color = Color3.fromRGB(120, 200, 40) }, + }, + -- Слоты апгрейда: в каждый перетаскивается деталь из инвентаря. required — слот не бывает пустым. + -- color — цвет слота и всех его деталей в меню; в этом же порядке сортируется инвентарь. + Slots = { + { id = "front", name = "ПЕРЕД", color = Color3.fromRGB(225, 75, 55) }, + { id = "wheels", name = "КОЛЁСА", required = "wheels_std", color = Color3.fromRGB(70, 145, 235) }, + { id = "rear", name = "ЗАД", color = Color3.fromRGB(95, 195, 85) }, + { id = "armor", name = "БРОНЯ", color = Color3.fromRGB(175, 105, 230) }, + { id = "weapon", name = "ОРУЖИЕ", required = "mg_light", color = Color3.fromRGB(235, 165, 40) }, + }, + -- Детали. id сохраняется в DataStore — не переименовывайте. starter — есть у всех с самого начала, + -- остальные закрыты: покупаются за осколки (price) или выдаются отдельно (из кейса: kind = "part", part = id). + -- speed — множитель максимальной скорости, armor — бронелисты гасят попадания по водителю. + -- gun — пушка на турели: kind ("bullet" — мгновенное попадание, "shell"/"rocket" — летящий снаряд со взрывом), + -- fireRate — выстрелов в секунду, damage — урон (у снарядов — в центре взрыва), spread — разброс в градусах, + -- heatPerShot — нагрев за выстрел (1 — перегрев), blastRadius — радиус взрыва, speed — скорость снаряда. + -- stats — вклад в характеристики (см. Stats ниже): offroad, durability, handling, firepower. + Parts = { + { id = "spikes", slot = "front", name = "Шипы", icon = "🔺", info = "Шипованный бампер", starter = true, + stats = { durability = 5, firepower = 5 } }, + { id = "ram", slot = "front", name = "Таран", icon = "🧱", info = "Наклонный отвал из листа железа", starter = true, + stats = { durability = 15, handling = -5 } }, + { id = "bucket", slot = "front", name = "Ковш", icon = "⛏️", info = "Ковш с зубьями — сгребает всё на пути (−5% скорости)", price = 150, speed = 0.95, + stats = { durability = 10, offroad = 10, handling = -10 } }, + { id = "bayonets", slot = "front", name = "Штыки", icon = "🗡️", info = "Длинные штыки вперёд", price = 200, + stats = { firepower = 12 } }, + { 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 } }, + { 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 } }, + { id = "grille", slot = "rear", name = "Решётка", icon = "🔳", info = "Защитная решётка над мотором", starter = true, + stats = { durability = 8 } }, + { id = "hood", slot = "rear", name = "Бронекрышка", icon = "🛡️", info = "Бронированное перекрытие кормы", armor = true, price = 180, + stats = { durability = 18, handling = -3 } }, + { 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 } }, + { id = "armor_heavy", slot = "armor", name = "Тяжёлая броня", icon = "🏰", info = "Борта и бронещиток спереди (−15% скорости)", armor = true, speed = 0.85, price = 350, + stats = { durability = 50, handling = -15 } }, + { 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, + gun = { kind = "bullet", fireRate = 7, damage = 14, spread = 0.5, heatPerShot = 0.06 }, stats = { firepower = 45 } }, + { id = "mg_twin", slot = "weapon", name = "Спаренные автоматы", icon = "⚔️", info = "Два ствола — шквал огня, но с разбросом", price = 400, + gun = { kind = "bullet", fireRate = 16, damage = 8, spread = 1.4, heatPerShot = 0.04, twin = true }, stats = { firepower = 55 } }, + { id = "cannon", slot = "weapon", name = "Пушка", icon = "💣", info = "Тяжёлый снаряд со взрывом, медленная перезарядка", price = 600, + gun = { kind = "shell", fireRate = 0.8, damage = 45, spread = 0.3, heatPerShot = 0.2, blastRadius = 8, speed = 320 }, stats = { firepower = 70, handling = -3 } }, + { id = "rockets", slot = "weapon", name = "Ракетница", icon = "🚀", info = "Ракеты с большим радиусом взрыва", price = 800, + gun = { kind = "rocket", fireRate = 1.2, damage = 35, spread = 0.6, heatPerShot = 0.25, blastRadius = 13, speed = 140, twin = true }, stats = { firepower = 85, handling = -3 } }, + }, + -- Характеристики в меню гаража (0–100): base + сумма stats установленных деталей. + -- Скорость считается отдельно — из множителей speed деталей. + Stats = { + { id = "offroad", name = "Проходимость", base = 35, color = Color3.fromRGB(95, 195, 85) }, + { id = "durability", name = "Прочность", base = 30, color = Color3.fromRGB(175, 105, 230) }, + { id = "handling", name = "Манёвренность", base = 55, color = Color3.fromRGB(70, 145, 235) }, + { id = "firepower", name = "Вооружённость", base = 0, color = Color3.fromRGB(225, 75, 55) }, + }, +} + +-- Зомби на картах команд: появляются, когда команда выехала, бегут к ближайшему игроку и бьют вблизи. +Config.Zombies = { + StartDelay = 6, -- секунд после старта: игроки успевают пройти заставку загрузки + Base = 8, -- сколько зомби одновременно на карте + PerPlayer = 4, -- и ещё столько на каждого игрока команды + Max = 30, + SpawnDistance = { 90, 170 }, -- на каком расстоянии от игрока появляются новые (вне поля зрения вблизи) + RespawnDelay = 3, -- через сколько секунд после смерти зомби на его место приходит новый + Health = 60, + WalkSpeed = { 10, 16 }, -- у каждого своя, в этих пределах + SightRange = 260, -- дальше этого игроков не замечают и бредут к ним медленно + AttackRange = 6.5, + AttackDamage = 8, + AttackCooldown = 1.1, + RamSpeed = 14, -- с какой скорости багги сбивает зомби + RamDamage = 2.2, -- урон тараном = (скорость − RamSpeed) × это, детали спереди добавляют сверху + ShardsPerKill = 2, -- награда убившему + Color = Color3.fromRGB(105, 135, 85), +} + +-- Осколки — внутриигровая валюта: открывают закрытые детали и покраски. +-- Выпадают на колесе фортуны и из кейсов (kind = "shards", amount = N). +Config.Shards = { + Start = 150, -- сколько у игрока с самого начала + Icon = "💎", +} + +-- Деталь по id +Config.PartById = {} +for _, item in Config.Garage.Parts do + Config.PartById[item.id] = item +end + +-- Лобби в ангаре: круги со стенками, у каждого круга — своя карта для команды. +Config.Lobby = { + Radius = 6, -- радиус круга, studs + WallHeight = 10, -- выше прыжка, чтобы игрок в лобби не перепрыгнул стенку + MaxPlayers = 4, + Countdown = 5, -- секунд от заполнения лобби до отправки на карту + MapSpacing = 2048, -- карты команд стоят в ряд по X от основной пустоши + Colors = { + Color3.fromRGB(60, 210, 120), + Color3.fromRGB(70, 150, 255), + Color3.fromRGB(230, 80, 210), + }, +} + +-- Колесо фортуны в ангаре: призы — редкие покраски (по имени из Config.Garage.Paints), «Кейс» или «Пусто». +Config.Fortune = { + Cooldown = 4 * 60 * 60, -- раз в 4 часа, секунд + SpinTime = 6, + Sectors = { "Хром", "Кейс", "Золото", "50 💎", "Лава", "Кислота", "150 💎", "Лёд", "Карбон" }, + -- Вес сектора (по умолчанию 1): и шанс, и ширина сектора на колесе. + Weights = { ["Кейс"] = 1.4, ["50 💎"] = 1.4, ["150 💎"] = 0.7 }, + -- Сектора с осколками: название → сколько дают. + Shards = { ["50 💎"] = 50, ["150 💎"] = 150 }, +} + +-- Кейсы: копятся у игрока (выпадают на колесе), открываются только ключом за Robux. +Config.Cases = { + -- ID developer product «Ключ от кейса» (Creator Dashboard → игра → Monetization → Developer Products). + ProductId = 0, + -- Содержимое: { name = "Золото", weight = 1, kind = "paint", paint = "Золото" } + -- или деталь: { name = "Гусеницы", weight = 1, kind = "part", part = "tracks" } + -- или осколки: { name = "300 осколков", weight = 1, kind = "shards", amount = 300 }. + -- kind — способ выдачи (см. Cases.Rewards на сервере). Пока список пуст, открытие выключено. + Loot = {}, +} + +Config.FlipCooldown = 2 + +return Config diff --git a/Zombi/src/shared/GunMath.luau b/Zombi/src/shared/GunMath.luau new file mode 100644 index 0000000..547adfc --- /dev/null +++ b/Zombi/src/shared/GunMath.luau @@ -0,0 +1,31 @@ +-- Наведение пулемёта: одна и та же математика на клиенте (прицел) и сервере (выстрел). + +local Config = require(script.Parent.Config) + +local G = Config.Gun +local GunMath = {} + +GunMath.Mount = CFrame.new(0, 1.9, -3.2) -- точка крепления турели относительно рамы +GunMath.Muzzle = CFrame.new(0, 0.25, -4.6) -- срез ствола относительно турели + +-- Углы турели (рад) в системе рамы для направления worldDir, с учётом ограничений. +-- Третий результат — попадает ли направление в сектор обстрела без обрезки. +function GunMath.Angles(chassisCFrame: CFrame, worldDir: Vector3): (number, number, boolean) + local d = chassisCFrame:VectorToObjectSpace(worldDir).Unit + local yaw = math.atan2(-d.X, -d.Z) + local pitch = math.asin(math.clamp(d.Y, -1, 1)) + local clampedYaw = math.clamp(yaw, -math.rad(G.YawLimit), math.rad(G.YawLimit)) + local clampedPitch = math.clamp(pitch, math.rad(G.PitchMin), math.rad(G.PitchMax)) + return clampedYaw, clampedPitch, clampedYaw == yaw and clampedPitch == pitch +end + +function GunMath.Rotation(yaw: number, pitch: number): CFrame + return CFrame.Angles(0, yaw, 0) * CFrame.Angles(pitch, 0, 0) +end + +-- Мировой CFrame турели (смотрит туда, куда стволы). +function GunMath.Turret(chassisCFrame: CFrame, yaw: number, pitch: number): CFrame + return chassisCFrame * GunMath.Mount * GunMath.Rotation(yaw, pitch) +end + +return GunMath