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

How do you detect a player holding a keybind?

I am trying to make a Blade, and when you hold Q it charges an attack, more time = bigger attack. But I am really confused at the moment, because I am doing a "TakeoHonorable" Type gear (Person who made the periastrons) so luckymaxer's (or RBLXLucky's) gear which involves holding down the mouse will not help me at all :C.

Current Code so far!

Tool.Strike.OnServerEvent:Connect(function(Client,KeyCode) --Registers ability from LocalScript
	if not KeyCode then return end
	if KeyCode == Enum.KeyCode.Q and Handle.Particle.Flare.Enabled == true then
		Handle.SunCharge:Play()
		Tool.Enabled = false
		
		LeftDown = true
		local HoldTime = 0
		while LeftDown do
			HoldTime = HoldTime + Heartbeat:wait()
			if HoldTime >= 6 then
				break
			elseif HoldTime <= 3 then
				break
			elseif HoldTime <= 1 then
				break
			end
		end
	end
end)

you never know, this might be a good code, or it will go horribly!

1 comment

0

Meanwhile this stays up, i will update my code a bit, so this may be outdated

1 answer

Alright, you should be detecting ANY input on the Client, not the Server. You would send the result then to the server instead.


The best way to detect a key being held is probably using UserInputService. It has the method called IsKeyDown(), IsMouseButtonPressed(), and IsGamepadButtonDown() (or something like that).


EXAMPLE

Client

local UIS = game:GetService("UserInputService")
local runService = game:GetService("RunService")

local holding = false

UIS.InputBegan:Connect(function(input, gameProcessedEvent)
	if gameProcessedEvent then return end

	if input.KeyCode == Enum.KeyCode.Q then --// You can change the keycode
		holding = true
	end
end)

UIS.InputEnded:Connect(function(input, gameProcessedEvent)
	if gameProcessedEvent then return end

	if input.KeyCode == Enum.KeyCode.Q then --// You can change the keycode
		holding = false
	end
end)

while true do
	if holding then
		--// Do stuff while holding
	else
		--// Do stuff while NOT holding
	end
	runService.Heartbeat:Wait()
end

This requires UserInputService to detect Client Input, and RunService for 60 FPS instead of the 30 FPS wait().

Then we just detect their input when they're not typing (if gameProcessedEvent then return end stops the code from running when it's chat input) and check if they're pressing the correct key. - If they are, we set it to true/false (Began/Ended)

And then we just have a while loop checking if they're holding it or not by checking the bool variable we set above.


Hope this helped! Don't forget to mark this as an answer if this helped you!

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