Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How I play an animation while pressing on a key on my keyboard?

local player = game.Players.LocalPlayer

local mouse = player:GetMouse()

function onkey(key)

if key == "b" -- change to whatever key you want to trigger the function--

then

    player.Character.Humanoid.WalkSpeed = 16 * 2.5

        endend

mouse.KeyDown:connect(onkey)

local player = game.Players.LocalPlayer

repeat wait() until player.Character

local character = player.Character

local animation = Instance.new("Animation")

animation.AnimationId = "1898738866"

local track = character:FindFirstChild("Humanoid"):LoadAnimation(animation) UIS.InputBegan:connect(function(input, proc)

if not proc then -- So that it wont fire when the player is chatting

    if input.KeyCode == Enum.KeyCode.B then --We will see if the key pushed is "B"

        track:Play()

        character.Humanoid.WalkSpeed = 16 * 2.5

    end

end

end) This is what I've tried but it hasn't worked. I put it in workspace. Please tell me what I did wrong!!

3 comments

0

Put it into a code block next time

0

And judging by the comments, I'm assuming this isn't your code

0

Use UserInputService instead.

1 answer

✓ Accepted answer

KeyDown and connect are deprecated, here is a remote event + non deprecated code

— LocalScript

local remote = game:GetService(“ReplicatedStorage”).PlayAnim
local plr = game:GetService(“Players”).LocalPlayer
local UIS = game:GetService”UserInputService”
local ContextActionService = game:GetService”ContextActionService”

function playAnim()
    remote:FireServer(game:GetService(“ReplicatedStorage”).Animation) 
end

ContextActionService:BindAction(“PlayAnim”, 
    playAnim, 
    false, 
    Enum.KeyCode.B)

This next one should go in ServerScriptService

—Server Script, deals with the animation playing.

local remote = game:GetService(“ReplicatedStorage”).PlayAnim

remote.OnServerEvent:Connect(function(player, anim)
    local animTrack = game.Workspace[player.Name].Humanoid:LoadAnimation(anim)
    animTrack:Play()
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.