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

按下空格键后部件仍旋转的Roblox脚本问题求助

问题分析与解决

你的脚本失效的核心原因有两个:

  • 脚本类型错误:UserInputService是客户端专属服务,只能在LocalScript中使用。如果你的脚本是普通Script(服务器端脚本),InputBegan事件根本不会触发,自然调用不了stopAndGo函数,state变量也就永远是true。
  • 旋转参数错误:CFrame.fromEulerAnglesXYZ的参数是弧度值,你传入的255是角度,会导致部件旋转速度极快,就算state切换了,视觉上也很难察觉停止效果。

修正后的代码

把脚本改成LocalScript,然后调整旋转参数,代码如下:

local spinning = script.Parent
local state = true
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

local function stopAndGo()
    state = not state
end

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
    if not gameProcessedEvent and input.KeyCode == Enum.KeyCode.Space then
        stopAndGo()
    end
end)

-- 用RunService.Heartbeat代替while循环,旋转更流畅
RunService.Heartbeat:Connect(function(deltaTime)
    if state then
        -- 把角度转成弧度,这里用5度每秒的速度旋转,可自行调整
        local rotation = CFrame.fromEulerAnglesXYZ(math.rad(5) * deltaTime, 0, 0)
        spinning.CFrame = spinning.CFrame * rotation
    end
end)

关键改动说明

  • 切换脚本类型:将原脚本替换为LocalScript,并放在PlayerScripts、StarterPlayerScripts或者部件的子级(只要客户端能加载到)。
  • 修正旋转逻辑:用math.rad()把角度转换成弧度,同时结合deltaTime让旋转速度和帧率无关,保证不同设备上旋转速度一致。
  • 优化循环方式:RunService.Heartbeat是每帧触发一次的事件,比while true wait(0.03)更稳定,避免因等待时间固定导致的卡顿。

另外,如果你一定要用服务器脚本控制旋转,可以通过RemoteEvent实现:客户端捕获空格键输入,发送信号给服务器,服务器再切换旋转状态。不过对于这种只需要客户端视觉效果的旋转,用LocalScript更高效。

内容的提问来源于stack exchange,提问作者Miguel Level Up

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 07:57:33