I am currently working on a crawling script for my game. I have a LocalScript in StarterPack with an Animation in the LocalScript. In my code, it starts playing the animation when Z is pressed once, but when it is pressed a second time it should stop but doesn't. In the output, it doesn't print ("Z was pressed again") after it's pressed a second time. The animation is looped, is in R15, and the priority is action. Here is what I currently have.
function KeyPress(input, gameProcessed) local pressed = 0 local animation game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(script.Animation) if input.KeyCode == Enum.KeyCode.Z then pressed = 1 print("Z was pressed") animation:Play() else if input.KeyCode == Enum.KeyCode.Z and pressed == 1 then pressed = 0 animation:Stop() print("Z was pressed again") end end end game:GetService("UserInputService").InputBegan:Connect(KeyPress)
If anybody knows why this is not working it would be greatly appreciated if you answered.
It seems like you want to implement a toggle, where a keypress would toggle the animation on or off. Here's how that should work:
local toggle = true -- toggle starts as turned on function onKeyPress() if toggle == true then -- if toggle is on toggle = false -- turn it off else toggle = true -- if toggle is off, turn it on end end
To apply that to your animation, the toggle is whether or not the animation is playing, and the keypress is the Z key. So you'd implement it like so:
And here's how your code looks like, with that implementation:
function KeyPress(input, gameProcessed) local animation = game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(script.Animation) if input.KeyCode == Enum.KeyCode.Z then -- Z key was pressed if animation.IsPlaying then animation:Play() else animation:Stop() end end end game:GetService("UserInputService").InputBegan:Connect(KeyPress)
Hope that helps!
function KeyPress(input, gameProcessed) local pressed = 0 local animation local animation_name = script.Animation.Name game.Players.LocalPlayer.Character.Humanoid:LoadAnimation(script.Animation) if input.KeyCode == Enum.KeyCode.Z then pressed = 1 print("Z was pressed") animation:Play() else if input.KeyCode == Enum.KeyCode.Z and pressed == 1 then pressed = 0 for i,v in pairs(game.Players.LocalPlayer.Character.Humanoid:GetPlayingAnimationTracks()) do if v.Name == animation_name then v:Stop() end end print("Z was pressed again") end end end game:GetService("UserInputService").InputBegan:Connect(KeyPress)
u can use get playing animation tracks to check what animations humanoid is playing then u can easily stop any animation you want. I have no idea what the animation name is so i used "script.Animation.Name" you can correct it on the line : "if v.Name == animation_name then" to : if v.Name == youranimationnamehere then