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

Trouble creating a toggle key?

I am new to scripting and have very little knowledge, but this is what i have so far:


wait(2)

local player = game.Players.LocalPlayer
local Mouse = player:GetMouse()
Anim = script.Animation

Mouse.KeyDown:connect(function(key)
if key == "q" then
local crouch = player.Character.Humanoid:LoadAnimation(Anim)
crouch:Play()
else
	local crouch = player.Character.Humanoid:LoadAnimation(Anim)
	crouch:stop()
end
end)

By the way, here's where its placed: StarterPack -> LocalScript -> Animation

I would like to have a toggle key to turn on and off crouching. I have looked up online tutorials, but found nothing about toggling an animation. Sorry if the script is cringey to look at, but i don't know much. So far, I am able to get the player to crouch when "Q" is pressed, but can't get it to stop. Any help? Thanks.

1 answer

There are two problems here: you're not checking if the Player's Character is crouching when Q is pressed, and you're reloading the Animation instead of saving a reference to it.

Assuming the Animation is looped, using AnimationTrack.IsPlaying will work for checking if the Player is crouching. Alternatively, you could store this in a variable and check and invert that.

wait(2)

local player = game.Players.LocalPlayer
local Mouse = player:GetMouse()
local Anim = script.Animation
local crouch

Mouse.KeyDown:connect(function(key)
	if not crouch then crouch = player.Character.Humanoid:LoadAnimation(Anim)
	if key == "q" then
		if crouch.IsPlaying then
			crouch:Stop()
		else
			crouch:Play()
		end
	end
end)

I would also suggest looking into the UserInputService for keyboard events, as PlayerMouse.KeyDown is deprecated.

1 comment

0

why did you use KeyDown if you said it was deprecated then?

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