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
local uis = game:GetService('UserInputService')
uis.InputBegan:connect(function(key)
if key.KeyCode == Enum.KeyCode.Q then
print("Q has been pushed!")
end
end)
uis.InputEnded:connect(function(key)
if key.KeyCode == Enum.KeyCode.Q then
print("Q has been released!")
end
end)
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.
local player = game.Players.LocalPlayer
player.CharacterAdded:connect(function(character)
local humanoid = character:WaitForChild('Humanoid')
local animation = humanoid:LoadAnimation(script.Parent.Animation)
animation:Play()
end)
COMBINED KNOWLEDGE
To roughly combine these, you would have the following script.
local player = game.Players.LocalPlayer
local uis = game:GetService("UserInputService")
player.CharacterAdded:connect(function(character)
uis.InputBegan:connect(function(key)
if key.KeyCode == Enum.KeyCode.R then
local humanoid = character:WaitForChild('Humanoid')
local animation = humanoid:LoadAnimation(script.Parent.Animation)
animation:Play()
end
end)
end)
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.
2 comments
please accept my answer
Have Done So. Thanks!