Roblox拳击动画无法停止:需实现左键交替播放单次左右拳动画
问题:拳击动画无法停止且无法交替触发左右拳
我的拳击动画无法停止,按下M1(左键)后会持续出拳。想要实现的效果是:点击一次仅播放左拳动画并停止,再次点击则播放右拳动画并停止,以此交替触发。
现有Lua脚本:
local plr = game.Players.LocalPlayer local UIS = game:GetService("UserInputService") local count = 0 local debounce = false UIS.InputBegan:Connect(function(Input, IS) if IS == true then return end if debounce == true then return end if Input.UserInputType == Enum.UserInputType.MouseButton1 then if count == 0 then spawn(function() wait(0.1) count = count + 1 end) game.ReplicatedStorage.CombatHit:FireServer() local animation = plr.Character.Humanoid:LoadAnimation(script.LeftPunch) animation:Play() print("Left Click") end if count == 1 then count = 0 if debounce == true then return end debounce = true game.ReplicatedStorage.CombatHit:FireServer() local animation = plr.Character.Humanoid:LoadAnimation(script.RightPunch) animation:Play() print("Left Click") wait(1) debounce = false end end end)
解决方案
原脚本的核心问题:
- 两个独立的
if语句无互斥,加上spawn的延迟更新,会导致状态切换混乱,可能触发多次动画。 - debounce仅作用于右拳逻辑,左拳无限制,导致连续点击触发多次左拳。
- 未处理动画叠加问题,也没有用动画自身的结束事件控制触发间隔。
修正后的脚本:
local plr = game.Players.LocalPlayer local UIS = game:GetService("UserInputService") local count = 0 -- 0代表下一次触发左拳,1代表右拳 local debounce = false local currentAnimation = nil -- 跟踪当前播放的动画实例 UIS.InputBegan:Connect(function(Input, IS) -- 忽略游戏内GUI输入或重复触发 if IS or debounce then return end if Input.UserInputType ~= Enum.UserInputType.MouseButton1 then return end debounce = true -- 停止上一次未播放完的动画,避免叠加 if currentAnimation then currentAnimation:Stop() currentAnimation = nil end local animationTrack -- 交替切换左右拳动画 if count == 0 then animationTrack = plr.Character.Humanoid:LoadAnimation(script.LeftPunch) game.ReplicatedStorage.CombatHit:FireServer() print("左拳动画播放") count = 1 else animationTrack = plr.Character.Humanoid:LoadAnimation(script.RightPunch) game.ReplicatedStorage.CombatHit:FireServer() print("右拳动画播放") count = 0 end currentAnimation = animationTrack animationTrack:Play() -- 等待动画播放完成后再允许下一次点击,确保单次点击只播放一次动画 animationTrack.Stopped:Wait() debounce = false currentAnimation = nil end)
关键修改说明
- 互斥逻辑:用
if-else替代两个独立if,确保每次点击只会触发左右拳中的一个,避免状态混乱。 - 全局debounce:点击开始就激活debounce,直到动画播放完成才释放,彻底防止连续点击触发多次动画。
- 动画叠加处理:每次点击前停止上一个动画,保证同一时间只有一个拳击动画播放。
- 精准触发间隔:利用动画的
Stopped事件代替固定wait,确保必须等当前动画播放完毕才能进行下一次操作,完全符合需求。
内容的提问来源于stack exchange,提问作者Shadow shadow.v
相关产品推荐
相关产品推荐

