Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to detect the mouse being held down?

Asked by
Mystdar 352 Moderation Voter
9 years ago

Just want to know the function/line for when the mouse is held down, and able to know when it is held and when it is brought back up again. Sorry if this has already been asked, I couldn't find it, thanks.

3 answers

Log in to vote
11
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

ROBLOX doesn't have a built in way to determine this, but writing it yourself is very easy.


The intuition is that a button is held down for the time between pressing it and releasing it.

mouseDown = false

startedDown = 0

-- `mouse` a Mouse object from, e.g., theLocalPlayer:GetMouse()

mouse.Button1Down:connect( function()
    mouseDown = true
    -- From now on, held
    startedDown = tick() -- Current time, in seconds
end)

mouse.Button1Up:connect( function()
    mouseDown = false
    -- From now on, NOT held
end)

while wait() do
    if mouseDown then
        print(
            "Has been held for ",
            tick() - startedDown,
            -- Time between now and when `startedDown` was set
            "seconds"
        )
    else
        print("Not held.")
    end
end
0
One question, how would I check if it has been held for, say, 3 seconds Mystdar 352 — 9y
2
Another variable that stores the time (time(), tick() or os.time()), and the difference between the current time and the stored time is how long it was held. Tkdriverx 514 — 9y
1
Sorry, you have lost me, however if you could provide an answer that just does what you said, then i'll upvote it. Mystdar 352 — 9y
3
Answer amended to include the time held for. BlueTaslem 18071 — 9y
1
Thank you Mystdar 352 — 9y
Ad
Log in to vote
0
Answered by 5 years ago

Alright, so while BlueTaslem's code works, I think this way is a bit more elegant, although, me being a really bad coder, his is probably more efficient or whatever..

inptSrvc = game:GetService("UserInputService")

while true do
    if inptSrvc:IsMouseButtonPressed(0) then
        --Your script
    end
end

"--Your script" will run while the left mouse button is being held

0
There is a problem with your script, and that is, if the player stops holding down the mousebutton, you cannot end the event that you have placed. So I recommend adding an elseif not function as well. 7_c 37 — 5y
Log in to vote
0
Answered by 3 years ago

As RarePlutonian said, The working script should be the following, Tho you have to cancel the script if the button isn't being held. That is very simple you can just do

inptSrvc = game:GetService("UserInputService")

while true do
    if inptSrvc:IsMouseButtonPressed(0) then
        --Your script
    else
        print('Not being held')
    end
end
0
you can change the ELSE code into something else it doesn't matter as long as it workss dementoslav 0 — 3y

Answer this question