How to check if mouse is being held for a certain time

I have a basic script to detect when the mouse is held and send a raycast.

local function mineBlock()
	UserInputService.InputBegan:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.MouseButton1 then
			held = true
			while held do
				wait()
				RayCastSetup()
			end
		end
	end)
	
	UserInputService.InputEnded:Connect(function(input)
		if input.UserInputType == Enum.UserInputType.MouseButton1 then
			held = false
		end
	end)
end

I want the raycast to be sent only after 5 seconds is up and only 1 raycast to be send, but Iā€™m not sure how to implement this. If I add a basic wait(5) I can click multiple times and backlog the while function

1 Like
local UserInput = game:GetService("UserInputService")
local HeldStartTime =  0

local function Clicked()
    HeldStartTime = os.time()

    local TemporarySave = HeldStartTime
    task.wait(5)
    if HeldStartTime == TemporarySave then
       RayCastSetup()
    end
end

UserInput.InputBegan:Connect(function()
   if input.UserInputType == Enum.UserInputType.MouseButton1 then
      Clicked()
   end
end)

This should work.
The script saves the os.time() and then uses task.wait(5) to wait the 5 seconds required. When the 5 seconds is up, the script then checks to see if the Click from the start of the function is the most recent.

YOU WILL NEED TO ADD THIS TO THE CODE

UserInput.InputEnded:Connect(function()
   if input.UserInputType == Enum.UserInputType.MouseButton1 then
      HeldStartTime = 0
   end
end)
2 Likes

Im not very familiar with os.time() so I ended up using a heartbeat function that is always checking the passed time between each hold

RunService.Heartbeat:Connect(function(dt)
		if held then
			mouseTimer = mouseTimer + dt
			if mouseTimer >= heldCountdown then
				print("worked")
				mouseTimer = 0
			end
		end
	end)

os.time() just Returns how many seconds have passed since the Unix epoch (1 January 1970, 00:00:00) under current UTC time.

Eg: At this minute the os.time() will return the value: 1685043575

I ended up getting the system to work. Thank you!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.