Hello, after a year and a half without touching a script, I’m starting to learn how to script again.
I’m making a tool and I need to detect if the left mouse button is being held, not if it’s being clicked.
This is the script if you need it:
local mouse = game.Players.LocalPlayer:GetMouse ()
local done = false
mouse.Button1Down:Connect(function()
if done == false then
done = true
script.Parent.shoot:FireServer(mouse.Hit.p)
wait(0.2)
done =false
end
end)
How can I do this? Thank you and sorry if my English is bad.
Usually, to detect if the left mouse button is being held down I would use a while loop like so:
local mouse = game.Players.LocalPlayer:GetMouse()
local heldDown = false
mouse.Button1Down:Connect(function() -- When left mouse button is depressed we make heldDown equal true and loop through a while loop
heldDown = true
while heldDown do
wait()
print("Left mouse button is being held down")
end
end)
mouse.Button1Up:Connect(function() -- When left mouse button is released we make heldDown equal false, stopping the loop
heldDown = false
end)
There are many ways of doing this. I don’t want to overcomplicate stuff, but also don’t want to set a bad example, so here is what I would do:
local userInput = game:GetService("UserInputService") -- We're using the user input service, even if there are other ways to do this
local ticket = 0 -- We're using a ticket system here to make sure that clicks won't be confused with mouse being held
local timeHeld = 0.2 -- In seconds, this would be 200ms, set this to your liking, can also be set to 0
local isHolding = false -- This will be used to avoid firing the leftMouseButtonReleased function without the button being held
-- This code should run once the left mouse button BEGINS being held
function leftMouseButtonHeld()
isHolding = true
print("Left mouse button IS BEING held!")
-- Add your code here
end
-- This code should run once the left mouse button STOPS being held
function leftMouseButtonReleased()
if not isHolding then return end
isHolding = false
print("Left mouse button is NO LONGER being held!")
-- Add your code here
end
userInput.InputBegan:connect(function(input, gameProcessed)
if gameProcessed then return end
if input.UserInputType == Enum.UserInputType.MouseButton1 then
ticket = ticket + 1 -- Increase the ticket count, so that we can track if the user has actually held the mouse button or not
local currentTicket = ticket -- Stores the CURRENT ticket value. If the user stops holding the mouse button, this will change and fail the if check
if timeHeld > 0 then
delay(timeHeld, function()
if ticket == currentTicket then
leftMouseButtonHeld()
end
end)
else
leftMouseButtonHeld()
end
end
end)
userInput.InputEnded:connect(function(input, gameProcessed)
if gameProcessed then return end
if input.UserInputType == Enum.UserInputType.MouseButton1 then
ticket = ticket + 1
leftMouseButtonReleased()
end
end)