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

Left Click To Punch...Help?

Asked by 5 years ago
Edited 5 years ago

Hello, everyone.

I'm trying to create a punch event that doesn't require a tool to be selected, but instead, by left clicking the mouse in order to trigger the event. I've come across few tutorials that are repitive in the sense that they are all KeyCode activated with "q" or "e", however, I couldn't find or resolve my issue with using the mouse instead. Here is an example of what I am using:

local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local punchEvent = ReplicatedStorage:WaitForChild("PunchEvent")

local ready = true

local function punch(inputObject, gameProcessed)
    if inputObject.KeyCode == Enum.KeyCode.Q and ready then
        punchEvent:FireServer()
        ready = false
        wait(0.5)
        ready = true
    end
end

UserInputService.InputBegan:Connect(punch)

I'm pretty sure that the KeyCode doesn't reach Mouse events. I've been doing my research throughout the Roblox Scripting Wiki. All suggestions and recommendations are welcome. Thank you, for your time.

  • sparkevin

2 answers

Log in to vote
1
Answered by 5 years ago

you can use the Button1Down event of the player's mouse which listens for when the player's mouse is held down which is pretty much clicking the mouse.

--client

local player = game.Players.LocalPlayer
local mouse = player:GetMouse() -- get the mouse
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local punchEvent = ReplicatedStorage:WaitForChild("PunchEvent")

local ready = true

mouse.Button1Down:Connect(function() 
    if ready then
        punchEvent:FireServer()
        ready = false
        wait(0.5)
        ready = true
    end
end)
0
Thank you, good sir. :D sparkevin 36 — 5y
Ad
Log in to vote
0
Answered by
LawlR 182
5 years ago
Edited 5 years ago

While EXpodo1234ALT's answer is correct, UserInputService is recommended over using the Mouse. The reasons are stated here: https://developer.roblox.com/api-reference/class/Mouse.

To detect a mouse click using UIS (UserInputService), you need to check the input's UserInputType:

local uis = game:GetService("UserInputService")

leftClick = uis.InputBegan:Connect(function(input, gameProcessed)
    if input.UserInputType == Enum.UserInputType.MouseButton1 then
        print("Click")
    end
end)

To stop detecting left clicks within this function, simply :Disconnect from it.

leftClick:Disconnect()

If you want to connect to the function again at a later date, put it in another function.

leftClickFunction = function()
    -- leftClick function in here.
end
-- And then call it whenever you need it: leftClickFunction().

Answer this question