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

How to tell when a key isn't being pressed?

Asked by 8 years ago

I'm trying to create a new walk animation, which almost fully works. With the code I currently have, I can get the animation to play, loop and override the regular walk animation, but I can't get it to stop when the player isn't pressing a certain key. How do I get this to happen? The code below is what I am currently using.

--The Animation
local walkanim = Instance.new("Animation")
--animationlinkgoeshere will be replaced with the actual link
walkanim.AnimationId = "animationlinkgoeshere"
--Player
local plr = game.Players.LocalPlayer
--UserInputService
local uis = game:GetService('UserInputService')

--Input Function
function Input(i)
    --Check key
    if i.KeyCode == Enum.KeyCode.W then
        animTrack = plr.Character.Humanoid:LoadAnimation(walkanim) -- Load animation into Humanoid
        animTrack:Play()
    end
end

function onSelected()
    --Connect function
    uis.InputBegan:connect(Input)
end

script.Parent.Selected:connect(onSelected)

As you can see, I've made it so that the animation will play when W is pressed.

2 answers

Log in to vote
0
Answered by 8 years ago

You can use the InputEnded event of the UserInputService and check if the KeyCode is W and then stop the animation.

You will also need to make the animation track a global variable so you can stop the animation from a different scope of the script.


Final code:

--The Animation
local walkanim = Instance.new("Animation")
--animationlinkgoeshere will be replaced with the actual link
walkanim.AnimationId = "animationlinkgoeshere"
--Player
local plr = game.Players.LocalPlayer
--UserInputService
local uis = game:GetService('UserInputService')
local animTrack --Defining a local variable in the global scope of the script essentially makes it available for use anywhere in the script after setting it.

--Input Function
function Input(i)
    --Check key
    if i.KeyCode == Enum.KeyCode.W then
        animTrack = plr.Character.Humanoid:LoadAnimation(walkanim) -- Load animation into Humanoid
        animTrack:Play()
    end
end

function InputEnd(i)
    if i.KeyCode == Enum.KeyCode.W and animTrack then
        animTrack:Stop()
        animTrack = nil
    end
end

function onSelected()
    --Connect function
    uis.InputBegan:connect(Input)
    uis.InputEnded:connect(InputEnd)
end

script.Parent.Selected:connect(onSelected)

I hope my answer helped you. If it did, be sure to accept it.

0
This works perfectly, thank you. Ross1397 25 — 8y
0
No problem. Spongocardo 1991 — 8y
Ad
Log in to vote
0
Answered by 8 years ago

Set it up so that it will keep checking to see if i is still equal to W or somehow set up a .Changed so when i is no longer equal to W then it will stop the animation. If you want to stop the animation use animTrack:Stop()

Answer this question