UserInputService with multiple keys

Hi developers! So I’m trying to make a fuel system and I’m only testing with my own character. I’m using UserInputService to detect if the WASD keys were clicked, but when I click 2 at a time for example, the system increases in speed. How can I avoid this and go for having at least 1 clicked at a time?

local UIS = game:GetService("UserInputService")
local player = game.Players.LocalPlayer

local enabled = false

UIS.InputBegan:Connect(function(i, gp)
	if (not gp) then
		if i.KeyCode == Enum.KeyCode.W or i.KeyCode == Enum.KeyCode.S or i.KeyCode == Enum.KeyCode.A or i.KeyCode == Enum.KeyCode.D then
			enabled = true
			while task.wait() and enabled == true do
				if player.PlayerGui.Gas.Frame.Arrow.Rotation <= -250 then
					print(player.Name.." has no more gas!")
					break
				else
					player.PlayerGui.Gas.Frame.Arrow.Rotation -= 0.1
				end
			end
		end
	end
end)

UIS.InputEnded:Connect(function(i, gp)
	if (not gp) then
		if i.KeyCode == Enum.KeyCode.W or i.KeyCode == Enum.KeyCode.S or i.KeyCode == Enum.KeyCode.A or i.KeyCode == Enum.KeyCode.D then
			enabled = false
		end
	end
end)
1 Like

You have an amazing value enabled in your code which you made very good use of. You just need to add a statement to check it once more in the main input function.

I’ll let you try it out yourself, and if you truly want the answer I’ll mark it as spoiler below.

Here is where you need to add the check if (not gp) then
So it would become if (not gp and not enabled) then
This goes in InputBegan function ^^^

Thank you so much! Now it doesn’t go faster after multiple are clicked.

But if I click one and immediately change the key, the entire think stops until I click that key again. Is there a fix around this?

1 Like

Instead of using UIS.InputBegan, I think a loop would be better for your case.

This is how I would do it.

I would declare a variable which would be the main trigger for your while loop. Then I will bind a Heartbeat connection. The reason I chose heartbeat and not RenderStepped is because it’s the keyboard and not anything related to physics or screen rendering. Then I would make a quick check to see if they are in a text zone. If not, then we check if WASD and set enabled to true if yes, or else its false.

local UserInputService = game:GetService('UserInputService')

local enabled = false
game:GetService'RunService'.Heartbeat:Connect(function()
    if UserInputService:GetFocusedTextBox() return end -- if chatting/typing
    if UserInputService:IsKeyDown(Enum.KeyCode.W) or UserInputService:IsKeyDown(Enum.KeyCode.A) or UserInputService:IsKeyDown(Enum.KeyCode.S) or UserInputService:IsKeyDown(Enum.KeyCode.D) then
        enabled = true
    else
        enabled = false
    end
end)

while true do
    if enabled then
        -- do the stuff
    end
end
1 Like

Works! Thanks for your help!

char

1 Like