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

How to make a function where the player holds down a key?

Can't figure out how to make that function, could someone send me a link to the wiki or a video on how to do it (or just show how to do it), I've been looking and they're all horribly outdated. (Im making a brick move when you hold down either WASD) all I've done is this:

local tabDown = false local input = game:GetService("UserInputService") local player = game.Players.LocalPlayer local prog = 0 local RunService = game:GetService("RunService") move = workspace.CamPart.RemoteEvent cam = workspace.CamPart velocity = cam.BodyVelocity.Velocity event = Vector3.new(0,0,0)

input.InputBegan:connect(function(k) local key = k.KeyCode if key == Enum.KeyCode.A then tabDown = true event = Vector3.new(25,0,0) move:FireServer(event)

elseif key == Enum.KeyCode.D then tabDown = true event = Vector3.new(-25,0,0) move:FireServer(event) end end)

3 comments

0

Would it be mouse.KeyDown:connect(function(key) or no?

0

what do you exactly want to do?

0

Mouse.KeyDown is deprecated. UserInputService is both actively supported and more versatile.

1 answer

✓ Accepted answer

I typically wait for the user to press the key using InputBegan, and then store the key value as an index in a dictionary, and remove the index when the key is being released, which is discovered using InputEnded.

I then create a loop at the very bottom of the script. I check if the key is being held via if-statement by attempting to reference the key's name as an index in the dictionary. If it returns nil, then it's not being pressed. Otherwise, the if the conditional passes, then I can execute whatever I wish. Here's an example.

local UIS = game:GetService('UserInputService') --For easier reference
local KeysPressed = {}; --The table that we use to store our keys

UIS.InputBegan:Connect(function(Key, Process)
	if (Process) then return nil end;
	KeysPressed[Key.KeyCode.Name] = true;
	--If a GUI with Modal is visible, like in the menu, then this will not function.
end);

UIS.InputEnded:Connect(function(Key)
	--We don't need Process here, because if we return nil, then the user will be able to do freaky stuff, like allowing keys to be held by selecting another process.
	KeysPressed[Key.KeyCode.Name] = true;
end);

game:GetService('RunService').RenderStepped:Connect(function(Loop)
	if (KeysPressed('W') then
		print('W is being held.')
	end
	if (KeysPressed['A']) then
		print('A is being held.');
	end
	if (KeysPressed['S']) then
		print('S is being held.');
	end
	if (KeysPressed['D'] then
		print('D is being held.');
	end
end)

1 comment

0

Excuse the typo on line 16, I just edited this answer five times and it refuses to change. Change the condition to (KeysPressed['W']).

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