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

How can the Client hold down a key that plays the animation without it constantly playing?

Asked by
p0vd 207 Moderation Voter
5 years ago

What my problem here is that when ever I hold down the S key, (it plays an animation) it constantly plays from the start which I find really annoying. I'm not sure how I'm going to do this.

local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local humanoid = player.Character.Humanoid
local anim = Instance.new("Animation")
anim.AnimationId = "http://www.roblox.com/asset/?id=3398376417"
local holdingSKey = false

UIS.InputBegan:Connect(function(inputObject) 
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        holdingSKey = true
        while holdingSKey do
        local playAnim = humanoid:LoadAnimation(anim)
        playAnim:Play()
            wait(0.2)
        end
    end
end)

UIS.InputEnded:Connect(function(inputObject)
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        holdingSKey = false
    end
end)

2 answers

Log in to vote
0
Answered by
royaltoe 5144 Moderation Voter Community Moderator
5 years ago

AnimationTracks have an IsPlaying property. Create your animation track variable (playAnim) outside of the event and you should be able to use this property.

local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local humanoid = player.Character.Humanoid
local anim = Instance.new("Animation")
anim.AnimationId = "http://www.roblox.com/asset/?id=3398376417"
local holdingSKey = false

local playAnim = humanoid:LoadAnimation(anim)

UIS.InputBegan:Connect(function(inputObject) 
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        holdingSKey = true

        while holdingSKey do
        --Check if the animation is playing, if it's not, play the animation again
        if(not playAnim.IsPlaying)then
                playAnim:Play()
                wait(0.2)
        end
        end
    end
end)

UIS.InputEnded:Connect(function(inputObject)
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        holdingSKey = false
    end
end)
Ad
Log in to vote
-1
Answered by
Ankur_007 290 Moderation Voter
5 years ago

You could simply use the AnimationTrack.Looped property for this case:

local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer
local humanoid = player.Character.Humanoid
local anim = Instance.new("Animation")
anim.AnimationId = "http://www.roblox.com/asset/?id=3398376417"
anim = humanoid:LoadAnimation(anim)
anim.Looped = true

UIS.InputBegan:Connect(function(inputObject) 
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        anim:Play() -- This will keep looping until stopped
    end
end)

UIS.InputEnded:Connect(function(inputObject)
    if(inputObject.KeyCode==Enum.KeyCode.S)then
        anim:Stop() -- Simply stop the looping
    end
end)

Answer this question