Need help with detecting, if a/the button is being hold

I am trying to make a 2d game using sprites.
To move your character, you need to hold A or D…
But the problem is, you do not have to. You simply press a button (I do not want that by the way) and it moves by itself…

And that can cause problems, such as pressing two times, you get bonus speed and shakey screen…

local Player = game.Players.LocalPlayer
local UIS = game:GetService('UserInputService')

UIS.InputBegan:connect(function(input)
	if input.KeyCode == Enum.KeyCode.A then
		while input do
		task.wait(0.03)
			script.Parent.Position -= UDim2.new(0.003, 0, 0, 0)
			script.Parent.Parent.Position += UDim2.new(0.003*4, 0, 0, 0)
		end
	elseif input.KeyCode == Enum.KeyCode.D then
		while input do
			task.wait(0.030)
			script.Parent.Position += UDim2.new(0.003, 0, 0, 0)
			script.Parent.Parent.Position -= UDim2.new(0.003*4, 0, 0, 0)
			end
	elseif input.KeyCode == Enum.KeyCode.W then
		for i = 1, 10 do
			task.wait(0.030)
			script.Parent.Position += UDim2.new(0, 0, -0.006, 0)
		end
		for i = 1, 10 do
			task.wait(0.030)
			script.Parent.Position -= UDim2.new(0, 0, -0.006, 0)
		end
	end
end)

So how can I actually detect if the player is holding a/the button?

Hello
You can do this by making local values for a and d and then detecting whether they are true or false.

local uis = game:GetService('UserInputService')
local Player = game.Players.LocalPlayer

local a,d = false,false

uis.InputBegan:Connect(function(input,gpe)
	if not gpe then
		local key = input.KeyCode
		if key==Enum.KeyCode.A then
			a = true
		elseif key==Enum.KeyCode.D then
			d = true
		end
	end
end)
uis.InputEnded:Connect(function(input,gpe)
	if not gpe then
		local key = input.KeyCode
		if key==Enum.KeyCode.A then
			a = fasle
		elseif key==Enum.KeyCode.D then
			d = false
		end
	end
end)
while true do
	task.wait(.03)
	if a and not d then
		script.Parent.Position -= UDim2.new(0.003, 0, 0, 0)
		script.Parent.Parent.Position += UDim2.new(0.012, 0, 0, 0)
	elseif d and not a then
		script.Parent.Position += UDim2.new(0.003, 0, 0, 0)
		script.Parent.Parent.Position -= UDim2.new(0.012, 0, 0, 0)
	end
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.