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

Roblox Luau新手求助:按下F键播放动画(现有代码失效)

解决Roblox Luau按F键播放动画的问题

你的代码存在几个关键问题,其中LoadAnimation方法确实已被废弃,现在需要通过Humanoid.Animator对象加载动画。以下是修正后的完整方案:

原代码的问题点

  • 硬编码玩家名称:直接指定"Builderman"只能对单个玩家生效,应获取本地玩家(仅客户端脚本可用)
  • 未等待角色加载:脚本运行时角色可能还未生成,需监听CharacterAdded事件
  • 缺少按键触发逻辑:没有绑定F键的输入触发逻辑,原代码会直接播放而非按键触发
  • 使用过时API:Humanoid:LoadAnimation()已被废弃,现在需通过Animator加载动画

修正后的客户端脚本代码

local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")

-- 获取本地玩家(仅客户端脚本可用)
local player = Players.LocalPlayer
-- 等待角色生成或直接获取已存在的角色
local character = player.Character or player.CharacterAdded:Wait()
-- 等待Humanoid和Animator加载完成
local humanoid = character:WaitForChild("Humanoid")
local animator = humanoid:WaitForChild("Animator")

-- 创建动画实例并设置ID
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://16221843862"
-- 通过Animator加载动画轨道
local animationTrack = animator:LoadAnimation(animation)

-- 监听F键按下事件
UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
    -- 忽略UI交互时的输入(比如打字时按F不会触发)
    if gameProcessedEvent then return end
    -- 判断是否按下F键
    if input.KeyCode == Enum.KeyCode.F then
        -- 仅当动画未播放时触发,避免重复播放卡顿
        if not animationTrack.IsPlaying then
            animationTrack:Play()
        end
    end
end)

关键说明

  • 脚本需放在StarterPlayerScripts或StarterPack目录下(客户端脚本目录)
  • Animator是Humanoid的内置子对象,现在是Roblox加载动画的标准方式
  • UserInputService.InputBegan用于监听键盘输入,加入gameProcessedEvent判断可避免UI操作时误触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:42:36