Efficient way to make an automatic gun?

What’s the most efficient way to script an automatic gun? If the player holds down their left mouse key, it will keep firing until they let go. I was thinking to call a remote function with their mouse position everytime a new bullet needs to be created, but would that cause lag? I’m not sure if this is the only way.

3 Likes

Use UserInputService to detect key input. You do not need to make a physical bullet, Just a RayCast (Unless you wanna do bullet drop, which is trickier.)

One of the best places you can find a basic understanding of the concept is: Documentation - Roblox Creator Hub

If you have any further question just reply. Hope this helped.

1 Like

Yea but that does not say how to make it automatic though. And I don’t think the damage will replicate to the server if its a local script.

I’m honestly just confused on the loop-making part for the mousedown function. Could I loop it and send a remote event everytime a “bullet” is created? I’m not sure if this will create lag though.

Here’s some sample code to get you started. Basically, you want to have a “reload delay” to prevent overloading the server. The server should also have validity checks to make sure the raycasting is accurate, the client is firing at the right speed, ect. If you have questions, don’t hesitate to ask.

local lastFire = 0
local shootDelay = 1 / 3 --3 shots a second
local held = false

local function shoot()
    local now = tick()
    if now - lastFire >= shootDelay then
        lastFire = now
        --Run code to shoot
    else
        --Let use know they have to wait, if you want too
    end
end

game:GetService('UserInputService').InputBegan:Connect(function(i, gp)
    if not gp and i.UserInputType == Enum.UserInputType,MouseButton1 then
        shoot()
        held = true
    end
end)

game:GetService('UserInputService').InputEnded:Connect(function(i, gp)
    if not gp and i.UserInputType == Enum.UserInputType.MouseButton1 then
        held = false
    end
end)

game:GetService('RunService').Stepped:Connect(function()
    if held then
        shoot()
    end
end)

Resources to services used:

UserInputService.InputBegan
UserInputService.InputEnded
RunService.Stepped

18 Likes

Hello, how are you?, i have followed your script, but i ran into a question, should i put a FireServer() on the input began and then do the server checks and so on? Or how can i do the server checks?
Thanks in advance!!!

1 Like