You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Roblox stamina再生异常:静止/移动再生差异及WASD适配问题

问题分析与修复方案

核心问题

  1. isMoving状态未实时更新:脚本初始化时仅执行了一次isMoving的赋值逻辑,后续玩家按下/松开WASD键时,isMoving不会同步更新,导致再生逻辑始终使用初始值,无法根据移动状态切换再生速度。
  2. 再生逻辑嵌套错误:Shift松开后的再生循环里嵌套了静止再生的while循环,一旦进入该嵌套循环,就不会再检查玩家是否重新开始移动,导致再生速度无法切换回行走模式。
  3. 移动状态判断不可靠:仅通过WASD按键监听判断移动,忽略了手柄等其他输入方式,也没考虑按键按住但角色未移动的情况。

修正后的代码

local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local humanoid = char:WaitForChild("Humanoid")

local UIS = game:GetService("UserInputService")

local stamina = 250
local maxStamina = 250
local isRunning = false

-- 实时判断角色是否在移动
local function isCharacterMoving()
    return humanoid.MoveDirection.Magnitude > 0.1
end

--  stamina核心循环:处理消耗与再生
local function staminaLoop()
    while true do
        task.wait(0.1)
        stamina = math.clamp(stamina, 0, maxStamina)

        if isRunning then
            -- 跑步消耗逻辑
            if stamina > 0 then
                stamina -= 2
                humanoid.WalkSpeed = 32
            else
                isRunning = false
                humanoid.WalkSpeed = 16
            end
        else
            -- 非跑步时再生逻辑
            local moving = isCharacterMoving()
            if stamina < maxStamina then
                -- 静止时再生速度是行走时的2倍
                stamina += moving and 1 or 2
            end
        end

        -- 更新 stamina UI
        script.Parent:TweenSize(UDim2.new(stamina/maxStamina, 0, 1, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.1, true)
    end
end

-- 监听Shift启动/停止跑步
UIS.InputBegan:Connect(function(input, gameProcessed)
    if gameProcessed then return end
    if input.KeyCode == Enum.KeyCode.LeftShift and stamina > 0 then
        isRunning = true
    end
end)

UIS.InputEnded:Connect(function(input, gameProcessed)
    if gameProcessed then return end
    if input.KeyCode == Enum.KeyCode.LeftShift then
        isRunning = false
        humanoid.WalkSpeed = 16
    end
end)

-- 启动循环
task.spawn(staminaLoop)

关键改动说明

  • 改用Humanoid.MoveDirection判断移动:无论玩家用键盘、手柄哪种方式操作,只要角色实际移动,就能准确识别,避免了仅监听按键的局限性。
  • 独立的stamina循环:将消耗和再生逻辑整合到一个持续运行的循环中,每次循环都会重新判断状态,确保移动/静止、跑步/走路的状态变化能立刻反映到stamina的变化上。
  • 优化UI更新:给Tween添加true参数允许覆盖未完成的动画,避免UI卡顿;调整循环间隔平衡性能与流畅度。

内容的提问来源于stack exchange,提问作者Babydestroyer3k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:53:15