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

Any way to get the event of the mouse button being held down?

Asked by 6 years ago

I'd like to know if there's an event for TextButtons/ImageButtons that fire when the left mouse button is held down, as in you hold it down for a couple of seconds. I know MouseButton1Down, but that's not suiting for what I'm trying to do. What I'm trying to do is while the left mouse button is held down, a dummy model is rotated. The current script only fires when the mouse is clicked and not held down.

1local dummy = workspace.Dummy
2script.Parent.MouseButton1Click:Connect(function()
3    dummy:SetPrimaryPartCFrame(dummy.PrimaryPart.CFrame * CFrame.fromEulerAnglesXYZ(0,math.rad(3),0))
4end)

2 answers

Log in to vote
3
Answered by
Norbunny 555 Moderation Voter
6 years ago

Not sure if there's any easier way to do it, but all I've found was using UserInputService

01local inputService = game:GetService("UserInptuService")
02 
03local mouseDown = false
04 
05inputService.InputBegan:Connect(function(input))
06    if(input.UserInputType == Enum.UserInputType.MouseButton1) then
07        mouseDown = true
08        while mouseDown == true do
09            -- your code
10        end
11    end
12end)
13 
14inputService.InputEnded:Connect(function(input)
15    if(iinput.UserInputType == Enum.UserInputType.MouseButton1) then
16        mouseDown = false
17    end
18end

Explained:

1if(input.UserInputType == Enum.UserInputType.MouseButton1) then

Checks if the key pressed is the mouse's right button

1mouseDown = true
2        while mouseDown == true do
3            -- your code
4        end

changes the "mouseDown" variable's value to true, and lets your things happen while it's down/being held

1inputService.InputEnded:Connect(function(input)
2    if(iinput.UserInputType == Enum.UserInputType.MouseButton1) then
3        mouseDown = false
4    end
5end

Detects when the mouse button is no longer being held, and when it does, changes the variable's value, stopping the loop

Let me know if you need any extra help!

1
Alternatively you set a value to true/false and do while that value. Set true when MouseButton1Down, and set false when MouseButton1Up clc02 553 — 6y
0
Hadn't thought about that, good idea! Norbunny 555 — 6y
Ad
Log in to vote
2
Answered by
clc02 553 Moderation Voter
6 years ago

While UserInputService is good to know, this might be an easier way to understand.

01m1down = false
02 
03function doThing()
04  while m1down do
05    --Thing
06    wait()
07  end
08end
09 
10script.Parent.MouseButton1Down:Connect(function() m1down = true doThing() end)
11script.Parent.MouseButton1Up:Connect(function() m1down = false end)

Answer this question