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

Is there a way to test if a key is down in an if then statement?

Is there a way to test if a key is down in an if then statement? I tried to substitute the if then statement with a function, but the wait(.1) didn't work. I am trying to set off and explosion if the space bar has been help down after a jump. Any Ideas? this is a local script in StarterPlayerScripts.

local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local debounce = 0

humanoid.Jumping:connect(function(key)
	wait(.1)
	mouse.KeyDown:connect(function(key)
    	if key:lower() == " " then
			if debounce == 0 then
				debounce = 1				
				if not character:FindFirstChildOfClass("ForceField") then
					local ForceField = Instance.new("ForceField", character)
					ForceField.Visible = false
				end
				wait(0.2)
				local Explosion = Instance.new("Explosion", character)
				Explosion.Position = character.HumanoidRootPart.Position
				Explosion.Visible = false
				debounce = 0
			end
    	end
	end)
end)

2 comments

0

no

0

Helpful..

3 answers

✓ Accepted answer

You use UserInputService's IsKeyDown() function. You supply it with a KeyCode Enum and it'll check if that key is down.

For example:

local UIS = game:GetService("UserInputService")

while true do
	wait()
	if UIS:IsKeyDown(Enum.KeyCode.Space) then
		print("Space is currently held down on this loop.")
	end
end

The way you're currently doing it with Mouse can still be used with this, but it'll look pretty weird.

Wiki Link

1 comment

1

Thanks @ihatecars100!

humanoid.Jumping:connect(function()
	    wait(.1)
	    mouse.KeyDown:connect(function(key)
	        if key = key:lower(" ")  then

do this at the start instead this will check if you press down spacebar

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