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 5 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.

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

2 answers

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

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

local inputService = game:GetService("UserInptuService")

local mouseDown = false

inputService.InputBegan:Connect(function(input)) 
    if(input.UserInputType == Enum.UserInputType.MouseButton1) then
        mouseDown = true
        while mouseDown == true do 
            -- your code
        end
    end
end)

inputService.InputEnded:Connect(function(input)
    if(iinput.UserInputType == Enum.UserInputType.MouseButton1) then
        mouseDown = false
    end
end

Explained:

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

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

mouseDown = true
        while mouseDown == true do 
            -- your code
        end

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

inputService.InputEnded:Connect(function(input)
    if(iinput.UserInputType == Enum.UserInputType.MouseButton1) then
        mouseDown = false
    end
end

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 — 5y
0
Hadn't thought about that, good idea! Norbunny 555 — 5y
Ad
Log in to vote
2
Answered by
clc02 553 Moderation Voter
5 years ago

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

m1down = false

function doThing()
  while m1down do
    --Thing
    wait()
  end
end

script.Parent.MouseButton1Down:Connect(function() m1down = true doThing() end)
script.Parent.MouseButton1Up:Connect(function() m1down = false end)


Answer this question