How to make a raycast deviate randomly

im trying to make my gun system have random spread
i tried to use 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 =

local spreadAngle = math.rad(spreadValue)
local randomSpreadAngle = Random:NextNumber() * 2 * math.pi
local spreadVector = * 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 ="Part", workspace)
	Beam.BrickColor ="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 =, 0.075, Distance)
	Beam.CFrame =, TargetLocation) *, 0, -Distance/2)

	game.Debris:AddItem(Beam, 0.05)

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