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

[Solved myself] How can I detect if player is holding left mouse button?

I'm making a gun and I want it to rapid fire when player is holding left mouse button. I searched at devforum and developer hub but didn't find anything.

1 comment

0

Try looking up UserInputService then once you know how to detect inputs, look at IStarConquestI's answer

3 answers

By whatever method you are using to detect user inputs, you can have a variable that stores whether the mouse is down as a boolean value. Then, have a function that sets it to true when it detects the beginning of the click, and false when the end of the click is detected.

If you want this, then you need a script that detects input on left click that began and ended. You can see how long player has held the left click with a timer.

Use this:

local UIS = game:GetService("UserInputService")

local held = false
local timer = 0

UIS.InputBegan:Connect(function(key, gameproccessed)
if key.UserInputType == Enum.UserInputType.MouseButton1 and not gameproccessed then
held = true
end
end)

UIS.InputEnd:Connect(function(key, gameproccessed)
if key.UserInputType == Enum.UserInputType.MouseButton1 then
held = false
end
end)

while true do
wait()

if held then
timer = timer + 0.03
else
timer = 0
end

if timer >= 0.7 then -- you can modify the timer to whatever you like
--code here
end
end

2 comments

0

also i dont know how your script works if you're using remotes to begin it or shoot once, leave comment so i know

0

I already saw this on devforum, does not work.

Found a solution. This can be done by finding player's mouse and repeating fire() function. script would look like this:

function fire()
--code here
end

mouse.Button1Down:connect(function()
	hold = true
end)
mouse.Button1Up:connect(function()
	hold = false
end)

tool.Equipped:connect(function()
	tool.Activated:connect(function()
	repeat
	fire()
	wait()
	until hold == false
end)
end)

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