Ad
Still have questions? Join our Discord server and get real time help.
Log in to vote
0

How would I add spread to a raycasting gun?

Asked by
vogeln 0
6 days ago

I followed the ROBLOX Raycasting tutorial and made some edits to make it fully auto, but I can't figure out how to give it spread. Help?

This is my script.

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local tool = script.Parent

local mouseDown = false
local canPlay = true

mouse.Button1Down:Connect(function()
    mouseDown = true
end)

mouse.Button1Up:Connect(function()
    mouseDown = false
end)

tool.Equipped:Connect(function(mouse)
    while wait(0.1) do
        if mouseDown then
            if canPlay then
                canPlay = false

                tool.Sounds.Shoot:Play()
                local ray = Ray.new(tool.Barrel.CFrame.p, (mouse.Hit.p - tool.Handle.CFrame.p).unit * 300)
                local part, position = workspace:FindPartOnRay(ray, player.Character, false, true)

                local bullet = Instance.new("Part", workspace)
                bullet.BrickColor = BrickColor.new("New Yeller")
                bullet.FormFactor = "Custom"
                bullet.Material = "Plastic"
                bullet.Transparency = 0.9
                bullet.Anchored = true
                bullet.Locked = true
                bullet.CanCollide = false

                local distance = (tool.Barrel.CFrame.p - position).magnitude
                bullet.Size = Vector3.new(0.1, 0.1, distance)
                bullet.CFrame = CFrame.new(tool.Barrel.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)

                game:GetService("Debris"):AddItem(bullet, 0.1)

                if part then
                    local humanoid = part.Parent:FindFirstChild("Humanoid")

                    if not humanoid then
                        humanoid = part.Parent.Parent:FindFirstChild("Humanoid")
                    end

                    if humanoid then
                        humanoid:TakeDamage(34)
                    end
                end

                canPlay = true
            end
        end

    end
end)

0
use a little math.random() magic theking48989987 1853 — 6d

1 answer

Log in to vote
0
Answered by 6 days ago
Edited 6 days ago

When creating the ray, you can add a random component to the look vector:

local randomnum = math.random(2)-1

local randomvector = Vector3.new(randomnum,randomnum,randomnum)

local ray = Ray.new(tool.Barrel.CFrame.p, (mouse.Hit.p + randomvector  -tool.Handle.CFrame.p).unit * 300)

since math.random(num) returns a random number from >= 0 and <num, doing math.random(num)-num/2 will return a random number from -num/2 to num/2.

Ad

Answer this question