To play an animation when a key is pressed you would need to know three things. Animation Track, Animation Instance, and User Input Service. Now to load an animation onto the character you must first create the animation and make an animation track. This would be done by creating an animation instance and using the method :LoadAnimation() on the character's humanoid. This is how that would look:
local player = game.Players.LocalPlayer
repeat wait() until player.Character
local character = player.Character
local animation = Instance.new("Animation")
animation.AnimationId = "Roblox Animation Asset ID Here"
local track = character:FindFirstChild("Humanoid"):LoadAnimation(animation)
Now we have the track defined, but we want to use this animation whenever the player presses a certain key. Now we will use the user input service. The userinputservice is used to fire events and functions whenever the player interacts with their mouse,keyboard,touchscreen, ect. So to do this we first must get the service using the :GetService() method.
local UIS = game:GetService("UserInputService")
Now that we have the service we need to run our code whenever the player hit's a specific key. To do this we use the InputBegan listener. This will wait until a player has given the game any type of input, whether is be with the mouse, the keyboard, or a touch screen. We will connect this listener to a function whenever the event is fired. The InputBegan event passes 2 arguments, game processed event and the input. A game processed event is anything processed by the game itself, for example chatting in the chat box.
UIS.InputBegan:connect(function(input, proc)
if not proc then
if input.KeyCode == Enum.KeyCode.B then
track:Play()
character.Humanoid.WalkSpeed = 16 * 2.5
end
end
end)
So now lets put it all together into one chunk of code. We also will add in the debounce so the player doesn't spam it an potentially create lag and disorder
local player = game.Players.LocalPlayer
repeat wait() until player.Character
local character = player.Character
local deb = false
local animation = Instance.new("Animation")
animation.AnimationId = "Roblox Animation Asset ID Here"
local track = character:FindFirstChild("Humanoid"):LoadAnimation(animation)
local UIS = game:GetService("UserInputService")
UIS.InputBegan:connect(function(input,proc)
if not proc then
if input.KeyCode == Enum.KeyCode.B and deb == false then
deb = true
track:Play()
character.Humanoid.WalkSpeed = 16 * 2.5
wait(1)
deb = false
end
end
end)
Hope I Helped ~~Koolkid