Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to detect if player is pressing a key twice?

Asked by 5 years ago

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

Log in to vote
1
Answered by
BenSBk 781 Moderation Voter
5 years ago
Edited 5 years ago

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!

0
Yeah but, how do I make it so that the transform only happen when the key is pressed twice in a row? MArzalAlBuchariZ 33 — 5y
0
You could increment a counter when the key is pressed BenSBk 781 — 5y
Ad

Answer this question