# Help with shotgun raycast spread

Before you ask, yes I already have looked around for solutions but not a single one have been able to solve my problem.

I’m having trouble properly implementing spread on my shotgun. My old script works by getting the mouse position + random number between -1.5 and 1.5. The problem with that is since I’m adding to the mouse position, no matter how far it is, it’s as accurate as if you’re shooting at a close range.

The pseudocode would be like this:

``````local function getWorldMousePosition()

local mouseLocation = UIS:GetMouseLocation()
local screenToWorldRay = currentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
local directionVector = screenToWorldRay.Direction * MAX_DISTANCE
local raycastResult = workspace:Raycast(screenToWorldRay.Origin, directionVector, Params)
if raycastResult then
return raycastResult.Position
else
return screenToWorldRay.Origin + directionVector
end

end

local Origin = Barrel.Position
local Destination = getWorldMousePosition()

Destination.X + Random.new():NextNumber(-1.5, 1.5), -- X
Destination.Y + Random.new():NextNumber(-1.5, 1.5), -- Y
Destination.Z + Random.new():NextNumber(-1.5, 1.5) -- Z
)

local Direction = (Spread - Origin).Unit * Config["Range"]
``````

What I wanted to do was to take distance and angle into account.

I have absolutely no idea how to properly calculate shotgun spread. If you have your own, it would be helpful to see how you did it.

1 Like

I dont know either, but im giving it a shot

``````local Origin = Barrel.Position
local Destination = getWorldMousePosition() -- Vector3
local Dir = Destination - Origin

local ran = Random.new(math.random(1,(2^8)-1)

local function scatter(direction: Vector3, weight: number)
—direction : general direction
—weight: how close the random vector is to the general vector
return (ran.NextUnitVector() + direction.Unit*weight).Unit
end

local Direction = scatter(Dir,10)
``````