Answered by
8 years ago Edited 8 years ago
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:
1 | local player = game.Players.LocalPlayer |
2 | repeat wait() until player.Character |
3 | local character = player.Character |
5 | local animation = Instance.new( "Animation" ) |
6 | animation.AnimationId = "Roblox Animation Asset ID Here" |
7 | 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.
1 | 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.
1 | UIS.InputBegan:connect( function (input, proc) |
3 | if input.KeyCode = = Enum.KeyCode.B then |
5 | character.Humanoid.WalkSpeed = 16 * 2.5 |
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
01 | local player = game.Players.LocalPlayer |
02 | repeat wait() until player.Character |
03 | local character = player.Character |
05 | local animation = Instance.new( "Animation" ) |
06 | animation.AnimationId = "Roblox Animation Asset ID Here" |
07 | local track = character:FindFirstChild( "Humanoid" ):LoadAnimation(animation) |
08 | local UIS = game:GetService( "UserInputService" ) |
09 | UIS.InputBegan:connect( function (input,proc) |
11 | if input.KeyCode = = Enum.KeyCode.B and deb = = false then |
14 | character.Humanoid.WalkSpeed = 16 * 2.5 |
Hope I Helped ~~Koolkid