I need help with Keycodes

How would I be able to detect 2 keys being held down to print something out?
I’m trying to get A and D held down to print out “Hold”

UserInputService = game:GetService("UserInputService")

local aKeyPressed = false
local dKeyPressed = false
-----------------------------------------------------------------------------------
UserInputService.InputBegan:Connect(function(input,gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.A then
		aKeyPressed = true
		
		while aKeyPressed == true do
			wait()
			print("Left")
		end
	end	
end)

UserInputService.InputEnded:Connect(function(input,gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.A then
		aKeyPressed = false
	end
end) 
-----------------------------------------------------------------------------------
UserInputService.InputBegan:Connect(function(input,gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.D then
		dKeyPressed = true

		while dKeyPressed == true do
			wait()
			print("Right")
		end
	end	
end)

UserInputService.InputEnded:Connect(function(input,gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.D then
		dKeyPressed = false
	end
end) 

1 Like

Good question, and luckily it isn’t too difficult. You can use :IsKeyDown to check if the key is already held when the new input begins.

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
    if (input.KeyCode == Enum.KeyCode.A and UserInputService:IsKeyDown(Enum.KeyCode.D)) or (input.KeyCode == Enum.KeyCode.D and UserInputService:IsKeyDown(Enum.KeyCode.A)) then
        print('Hold')
    end
end)
1 Like