How to make a raycast deviate randomly

im trying to make my gun system have random spread
i tried to use random.new():NextNumber() but i couldn’t figure it out
code in a server script
targetlocation is the mouse location
i used to just add the spread value to the targetlocation but that makes it the same at all ranges which is not what i want

	local RayDirection = (TargetLocation  - Handles.Position) * raynge
1 Like

Hi, try this:

local Random = Random.new()

local spreadAngle = math.rad(spreadValue)
local randomSpreadAngle = Random:NextNumber() * 2 * math.pi
local spreadVector = Vector3.new(math.sin(randomSpreadAngle) * spreadAngle, 0, math.cos(randomSpreadAngle) * spreadAngle)
local rayDirection = (TargetLocation - Handles.Position).Unit + spreadVector
rayDirection = rayDirection.Unit
local finalDirection = rayDirection * raynge
1 Like

the system i use makes a part the length of the raycast but setting its cframe to finalDirection wont work

	local Beam = Instance.new("Part", workspace)
	Beam.BrickColor = BrickColor.new("New Yeller")
	Beam.FormFactor = "Custom"
	Beam.Transparency = 0
	Beam.Material = "Neon"
	Beam.Anchored = true
	Beam.CanCollide = false


	-- Math.
	local Distance = (Handles.Position - TargetLocation).magnitude
	Beam.Size = Vector3.new(0.075, 0.075, Distance)
	Beam.CFrame = CFrame.new(Handles.Position, TargetLocation) * CFrame.new(0, 0, -Distance/2)

	game.Debris:AddItem(Beam, 0.05)

I got back to testing and I believe this does not work