Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How would I make this animation stop when one of the keys are released?

Asked by
exarlus 72
5 years ago

This script plays an animation when 2 buttons are pressed. However I want the animation to stop whenever one of the keys are released.I tried doing "If not" for one of the keys.. but it still never works.

local uis = game:GetService('UserInputService')
local Player = game.Players.LocalPlayer
local Character = Player.Character
local human = Character:WaitForChild("Humanoid") 
 local Anim = script.WalkFoward

  PlayAnim = Character.Humanoid:LoadAnimation(Anim)



uis.InputBegan:Connect(function(input)
    if input.KeyCode == Enum.KeyCode.Z or input.KeyCode == Enum.KeyCode.X then
        local keys = uis:GetKeysPressed()
        local xFound, zFound
        for _, key in pairs(keys) do
            if key.KeyCode == Enum.KeyCode.Z then 
                zFound = true
            elseif key.KeyCode == Enum.KeyCode.X then
                xFound = true
            end
        end

        if zFound and xFound then
            PlayAnim:Play()
        end
    end
end)

1 answer

Log in to vote
1
Answered by 5 years ago

UserInputService:IsKeyDown(KeyCode) is what you are looking for. This will return a boolean. true for when the key is pressed, false otherwise.

local uis = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer
local Character = Player.Character
local human = Character:WaitForChild("Humanoid") 
local Anim = script.WalkFoward
local PlayAnim = Character.Humanoid:LoadAnimation(Anim)
local keysPressed = false
local xKey, zKey = Enum.KeyCode.X, Enum.KeyCode.Z

uis.InputBegan:Connect(function(input)

    if input.KeyCode == xKey or input.KeyCode == zKey then
        keysPressed = uis:IsKeyDown(xKey) and uis:IsKeyDown(zKey)

        while keysPressed do
            PlayAnim:Play()
            PlayAnim.Stopped:Wait()
        end
    end
end)

uis.InputEnded:Connect(function(input)
    if input.KeyCode == zKey or input.KeyCode == xKey then
        keysPressed = false
        PlayAnim:Stop()
    end
end)

Pretty much keysPressed will be true if both uis:IsKeyDown(xKey) and uis:IsKeyDown(zKey) return true, allowing the code in the while loop to execute. It just plays the animation and waits for it to stop to replay it. Of course you can change the behaviour to your liking

And on input ended just set keysPressed to false and stop the animation only if the Z key or X key is released

0
thanks exarlus 72 — 5y
Ad

Answer this question