So, what I'm wondering is how I can make the end of the ray (goes to mouse position) offset randomly, so when the gun fires, the ray will have a "spread", similar to actual guns. I already know how to use math.random, but I do not know where, and how to add the offset to the end of the ray.
local ray = Ray.new(tool.Handle.CFrame.p, (mouse.Hit.p - tool.Handle.CFrame.p).unit * 2048) local part, position = workspace:FindPartOnRay(ray, player.Character, false, true) local beam = Instance.new("Part", workspace) beam.BrickColor = player.TeamColor beam.FormFactor = "Custom" beam.Material = "Neon" beam.Transparency = 0 beam.Anchored = true beam.Locked = true beam.CanCollide = false local distance = (tool.Handle.CFrame.p - position).magnitude beam.Size = Vector3.new(0.1, 0.1, distance) beam.CFrame = CFrame.new(tool.Barrel.CFrame.p, position) * CFrame.new(0, 0, -distance / 2) game:GetService("Debris"):AddItem(beam, 0.1)
To get a random variation in the direction of the laser, you can multiply it by CFrame.Angles with random angles as the arguments. For example:
local Variation = 15 beam.CFrame = CFrame.new(tool.Barrel.CFrame.p, position) * CFrame.Angles(math.rad(math.random(-Variation,Variation)), math.rad(math.random(-Variation,Variation)), 0) * CFrame.new(0, 0, -distance/2)
this would rotate the beam up to 15 degrees on both the X and Y axes (you may have to swap the X with the Z if it rotates on the wrong axis). Basically, math.rad converts degrees to radians (which CFrame.Angles uses), and it's given a random number of degrees.
Hope this helps!
EDIT: to get more a more specific spread (like a hundredth of an increment), you can multiply by 100 before getting the random number and divide by 100 after. So, for example:
local Variation = 3 beam.CFrame = CFrame.new(tool.Barrel.CFrame.p, position) * CFrame.Angles(math.rad(math.random(-Variation*100,Variation*100)/100), math.rad(math.random(-Variation*100,Variation*100)/100), 0) * CFrame.new(0, 0, -distance/2)