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

How to detect if player is pressing a key twice?

I'm trying to transform a player if a player press the spacebar and I want both of the function to have the same key, so when the player press the spacebar twice on the first time, it will transform the player. But if the player presses the spacebar once after it has already transformed, the player will come back to its original state.

KeyPressed = 0

game:GetService("UserInputService").InputBegan:connect(function(input)
if input.KeyCode == Enum.KeyCode.Space then
for _, child in pairs(script.Parent:GetChildren()) do
	KeyPressed = 2
if child:IsA("UnionOperation") then
child.CanCollide = false
child.Transparency = 1
Animator.Parent = nil
Humanoid.HipHeight = 1
end
end
end
end)

game:GetService("UserInputService").InputBegan:connect(function(input)
if input.KeyCode == Enum.KeyCode.Space then
for _, child in pairs(script.Parent:GetChildren()) do
	KeyPressed = 1
if child:IsA("UnionOperation") then
child.CanCollide = false
child.Transparency = 0
Animator.Parent = Humanoid
Humanoid.HipHeight = 10.75
end
end
end
end)

1 answer

✓ Accepted answer

Use a boolean, and check and set this every time the Player presses the space bar. Here is an example:

-- Services:
local user_input_service = game:GetService("UserInputService")

-- Variables:
local is_transformed = false

-- Main:
user_input_service.InputBegan:Connect(function(input, is_game_processed)
	-- Check if input is game processed.
	if is_game_processed then
		return
	end
	-- Check if input isn't the space key.
	if input.KeyCode ~= Enum.KeyCode.Space then
		return
	end
	-- Check if the Player is transformed or not.
	if is_transformed then
		is_transformed = false
		-- Switch to original state.
	else
		is_transformed = true
		-- Switch to transformed state.
	end
end)

I hope that this helped!

2 comments

0

Yeah but, how do I make it so that the transform only happen when the key is pressed twice in a row?

0

You could increment a counter when the key is pressed

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