roblox studio напиши скрипт чтобы при нажатие на к...

Créé le : 28 août 2025

Répondu en utilisant GPT-5 Thinking par Chat01

Question

roblox studio напиши скрипт чтобы при нажатие на кнопку shift игрок начинал бежать. и шкалу чтобы через 5 секунд бежать больше нельзя было. заново можно бежать только через 7 секунд

Réflexion

Writing sprint script for Roblox

I’m planning the sprint script in Roblox using Lua: The player holds Shift to sprint, but after 5 seconds, stamina runs out, and they can only sprint again after a 7-second cooldown.

I’ll add stamina UI and adjust the player’s walking speed to 24 or 28 while sprinting. The LocalScript will manage input, stamina depletion, and UI updates.

Considering server authority versus LocalScript

I’m debating whether movement speed should be server-authoritative. Normally, speed changes are handled on the server to prevent exploits, but here, a LocalScript should be fine for simplicity.

For the stamina bar UI, I'll use a LocalScript to create the ScreenGui, with the necessary frames for the background and fill. I’ll also set up the player-related variables, like UIS for input and Players.

Sprint state management and UI updates

For the sprint script, stamina is at a maximum of 5 seconds, with a 7-second cooldown afterward. When the player presses Shift, the script will check if they can sprint and then adjust the WalkSpeed to sprint speed. If stamina hits 0, cooldown starts, and stamina regenerates after 7 seconds. I'll also manage the UI to show progress and cooldown. Even if the user releases Shift early, it seems the cooldown and stamina reset still apply — sprinting can’t happen for 7 seconds, regardless.

Sprint and stamina recovery mechanics

To match the spec, the stamina should only deplete while sprinting. If it reaches 0, sprinting is blocked and a 7-second cooldown begins. If the user releases Shift early, stamina stops depleting but won’t recover until the full cooldown ends. The design will prevent partial recovery to ensure sprinting can only happen again after 7 seconds of cooldown.

Sprint mechanics and UI setup

The sprinting will deplete stamina only while running, and if the user releases early, the remaining time stays. Once stamina runs out, the cooldown begins for 7 seconds before they can sprint again. I’ll add a UI to display stamina and cooldown via Script in StarterPlayerScripts. Stamina will freeze at 0 during cooldown and refill over time. I’ll prevent sprinting from restarting until cooldown is fully completed, and handle input from both Shift keys.

Implementing sprint script

I wrote a LocalScript that handles sprinting mechanics with stamina and cooldown, and shows a UI to track progress. The script will stop sprinting when stamina hits zero and engage a 7-second cooldown. I've added comments for clarity in Russian. It should be placed in StarterPlayerScripts.

Instructions:

  • Place the script in StarterPlayerScripts for proper input handling.

Let me know if you'd like extra refinements!

Thought for 1m 18s

Réponse

ниже — готовый LocalScript с полоской выносливости.
Что делает:

  • Зажимаешь Shift → скорость повышается (спринт).
  • Полоса выносливости тает 5 секунд. Когда дойдёт до нуля — спринт выключается.
  • Повторно спринт можно включить только после 7 секунд восстановления (полоса заполняется).
  • Работает и с левым, и с правым Shift.

Куда положить

Вставь LocalScript в StarterPlayer > StarterPlayerScripts (ничего больше создавать не нужно — GUI сделается скриптом).

lua
-- LocalScript в StarterPlayerScripts local Players = game:GetService("Players") local UIS = game:GetService("UserInputService") local RunService = game:GetService("RunService") local player = Players.LocalPlayer local character = player.Character or player.CharacterAdded:Wait() local humanoid = character:WaitForChild("Humanoid") -- ====== НАСТРОЙКИ ====== local STAMINA_MAX = 5 -- сек. непрерывного бега local COOLDOWN = 7 -- сек. перезарядки после исчерпания local SPRINT_MULT = 1.6 -- во сколько раз быстрее обычного -- ====== СОСТОЯНИЕ ====== local DEFAULT_SPEED = humanoid.WalkSpeed local SPRINT_SPEED = DEFAULT_SPEED * SPRINT_MULT local stamina = STAMINA_MAX local sprinting = false local inCooldown = false local shiftDown = false -- ====== GUI (создаётся скриптом) ====== local gui = Instance.new("ScreenGui") gui.Name = "SprintGui" gui.ResetOnSpawn = false gui.Parent = player:WaitForChild("PlayerGui") local barBg = Instance.new("Frame") barBg.Name = "BarBg" barBg.AnchorPoint = Vector2.new(0.5, 1) barBg.Position = UDim2.new(0.5, 0, 1, -60) barBg.Size = UDim2.new(0, 300, 0, 20) barBg.BackgroundColor3 = Color3.fromRGB(30, 30, 35) barBg.BackgroundTransparency = 0.2 barBg.BorderSizePixel = 0 barBg.Parent = gui local barFill = Instance.new("Frame") barFill.Name = "BarFill" barFill.Size = UDim2.new(1, 0, 1, 0) -- старт: полная шкала barFill.BackgroundColor3 = Color3.fromRGB(70, 200, 120) barFill.BorderSizePixel = 0 barFill.Parent = barBg local corner1 = Instance.new("UICorner") corner1.CornerRadius = UDim.new(0, 6) corner1.Parent = barBg local corner2 = Instance.new("UICorner") corner2.CornerRadius = UDim.new(0, 6) corner2.Parent = barFill local label = Instance.new("TextLabel") label.BackgroundTransparency = 1 label.Size = UDim2.new(1, 0, 1, 0) label.Font = Enum.Font.GothamBold label.TextScaled = true label.TextColor3 = Color3.new(1, 1, 1) label.Text = "Спринт: готов" label.Parent = barBg -- ====== ЛОГИКА ====== local function setSprint(on) if on and not inCooldown and stamina > 0 then sprinting = true humanoid.WalkSpeed = SPRINT_SPEED label.Text = "Бег" else sprinting = false humanoid.WalkSpeed = DEFAULT_SPEED if inCooldown then label.Text = "Перезарядка..." else label.Text = "Спринт: готов" end end end -- Обработка нажатий Shift UIS.InputBegan:Connect(function(input, gpe) if gpe then return end if input.KeyCode == Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.RightShift then shiftDown = true setSprint(true) end end) UIS.InputEnded:Connect(function(input, gpe) if input.KeyCode == Enum.KeyCode.LeftShift or input.KeyCode == Enum.KeyCode.RightShift then shiftDown = false setSprint(false) end end) -- Пересоздание персонажа player.CharacterAdded:Connect(function(char) character = char humanoid = character:WaitForChild("Humanoid") DEFAULT_SPEED = humanoid.WalkSpeed SPRINT_SPEED = DEFAULT_SPEED * SPRINT_MULT setSprint(false) end) -- Основной цикл: тратим выносливость при беге, запускаем КД, обновляем шкалу RunService.Heartbeat:Connect(function(dt) -- Тратим выносливость только во время спринта if sprinting and stamina > 0 and not inCooldown then stamina = math.max(0, stamina - dt) if stamina == 0 then -- Выносливость кончилась -> стоп и КД setSprint(false) inCooldown = true label.Text = "Перезарядка..." -- анимация перезарядки: шкала заполняется за COOLDOWN секунд task.spawn(function() local t = 0 while t < COOLDOWN do local step = task.wait(0.05) t = t + step local alpha = math.clamp(t / COOLDOWN, 0, 1) barFill.Size = UDim2.new(alpha, 0, 1, 0) end stamina = STAMINA_MAX inCooldown = false barFill.Size = UDim2.new(1, 0, 1, 0) -- если Shift всё ещё зажат — снова начать бег if shiftDown then setSprint(true) else setSprint(false) end end) end end -- Обновляем шкалу в обычном режиме (когда не на КД) if not inCooldown then barFill.Size = UDim2.new(stamina / STAMINA_MAX, 0, 1, 0) end end)

Примечания

  • По умолчанию скорость Roblox — 16; скрипт делает спринт ≈ в 1.6 раза быстрее. Хочешь быстрее/медленнее — поменяй SPRINT_MULT.
  • Если отпустить Shift раньше, выносливость не восстанавливается сама — добежать остаток можно позже. Как только шкала дойдёт до нуля, включится 7-секундная перезарядка.

Partager cette Q&R