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

Is it possible to check if a player is holding down a key? (SOLVED)

It sounds confusing I know, but read this to understand. I want to see that if a player holds down a key using the key: down event for 5 seconds, I want a action to happen. Is this even possible? And if so can you point me to the right direction?

2 answers

✓ Accepted answer

In a local script:

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

local down = {}

mouse.KeyDown:connect(function(key)
	--'tag' the time the key was pressed, set pressing to true
	down[key:lower()] = {pressing = true, tag = tick()}
end)

mouse.KeyUp:connect(function(key)
	--set pressing to false
	down[key:lower()] = {pressing = false, tag = 0}
end)

game:GetService("RunService").RenderStepped:connect(function()
	--loop through the keys
	for key, array in pairs(down) do
		--if the key is being pressed
		if array.pressing then
			print("\"" .. key .. "\" has been held for " .. tick() - array.tag .. " seconds.")
			if tick() - array.tag > 5 then
				print("ALERT: \"" .. key .. "\" has been held for more than 5 seconds!")	
			end
		end
	end
end)

Not very flexible and it can't tell if you let go and then re-held the key within the 5 seconds but it works...

local Key=nil
function KeyDown(K)
	Key=K
	wait(5)
	if Key then
		print(Key.." was held for 5 seconds")
	end
end
function KeyUp()
	Key=nil
end

2 comments

0

Awesome thank you so much!

0

I don't even think this would work. There aren't any events attached to the functions. Use mine, instead.

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