USER INPUT SERVICE
UIS, aka User Input Service
is the best way to go.
UIS is used in local scripts and can be triggered by InputBegan
, InputEnded
, and InputChanged
.
InputBegan
does as you would think. It will trigger when a button is pushed.
InputEnded
will trigger when a button is released.
InputChanged
will trigger when a button has been changed.
An example script would be
01 | local uis = game:GetService( 'UserInputService' ) |
03 | uis.InputBegan:connect( function (key) |
04 | if key.KeyCode = = Enum.KeyCode.Q then |
05 | print ( "Q has been pushed!" ) |
08 | uis.InputEnded:connect( function (key) |
09 | if key.KeyCode = = Enum.KeyCode.Q then |
10 | print ( "Q has been released!" ) |
ANIMATION
For animations, you must first define the humanoid, as you need to load the animation into the humanoid before you can play it. After you have defined the humanoid, you need to load the animation into it, which is commonly done when you're defining the animation. Then afterwards you need to play the animation.
1 | local player = game.Players.LocalPlayer |
2 | player.CharacterAdded:connect( function (character) |
3 | local humanoid = character:WaitForChild( 'Humanoid' ) |
4 | local animation = humanoid:LoadAnimation(script.Parent.Animation) |
COMBINED KNOWLEDGE
To roughly combine these, you would have the following script.
01 | local player = game.Players.LocalPlayer |
02 | local uis = game:GetService( "UserInputService" ) |
03 | player.CharacterAdded:connect( function (character) |
04 | uis.InputBegan:connect( function (key) |
05 | if key.KeyCode = = Enum.KeyCode.R then |
06 | local humanoid = character:WaitForChild( 'Humanoid' ) |
07 | local animation = humanoid:LoadAnimation(script.Parent.Animation) |
Keep in mind that this is not a complete script, and you would have to add this to your gun script, and make it more complex with the ammunition and the reload animation and all that.