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

How can I make a play and stop animation when a key is pressed?

Asked by 3 years ago

Hello, I am trying to make a gun that plays an animation when you press a key

The way I want it to work is that if a player presses the key E then an animation will play. If the player presses it again then it stops.

I have been trying to do this the past 4 hours and I would really appreciate it if you could help me :)

This is the code:

local keyPressed = 0

local tool = script.Parent
local uis = game:GetService("UserInputService")
local equipped = false 

local anim = Instance.new("Animation")
anim.AnimationId = "rbxassetid://7105053395"

tool.Equipped:Connect(function()
    equipped = true
end)

tool.Unequipped:Connect(function()
    equipped = false
end)

uis.InputBegan:Connect(function(key)
    local player = game.Players.LocalPlayer
    local char = player.Character
    local animTrack = char.Humanoid:LoadAnimation(anim)

    if equipped then
        if key.KeyCode == Enum.KeyCode.E and keyPressed == 0 then
            keyPressed = 1

            animTrack:Play()
            print("PLAYING")
        end
    end


    if key.KeyCode == Enum.KeyCode.E and keyPressed == 1 then
        keyPressed = 0

        animTrack:Stop()
        print("STOMPING")
    end

    if not equipped then
        animTrack:Stop()
    end
end)

Answer this question