Bullet spread doesn't work at max distance?

I’m working on a gun system that uses cone-shaped bullet spread. Right now I have an issue that whenever I fire at max distance, the bullet spread has no effect, but for some reason, it works perfectly when I shot any distance within the max range.

Demonstration:
(Results when shooting close)


(Results when shooting far)

local random = Random.new()
local function randomPointInEllipse(angle: number): Vector2
	local angle = random:NextNumber(0, math.pi * 2)
	local u = random:NextNumber() + random:NextNumber()
	local r = (u > 1 and 2 - u or u)
	local spreadRadians = Vector2.new(math.rad(angle), math.rad(angle))
	return Vector2.new(r * math.cos(angle) * spreadRadians.X, r * math.sin(angle) * spreadRadians.Y)
end

local function fireBullet()
	local TRAVEL_DISTANCE = 100
	
	local mouseLocation = UserInputService:GetMouseLocation()
	local viewportPointToRay = currentCamera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
	local viewportPointRaycast = Workspace:Raycast(viewportPointToRay.Origin, viewportPointToRay.Direction * TRAVEL_DISTANCE)
	local viewportPointIntersection = viewportPointRaycast and viewportPointRaycast.Position or viewportPointToRay.Origin + viewportPointToRay.Direction * TRAVEL_DISTANCE
	
	local muzzlePosition = muzzle.WorldPosition
	local spreadAngle = randomPointInEllipse(5)
	local bulletDirectionCFrame = CFrame.lookAt(muzzlePosition, viewportPointIntersection)
	local bulletDirection = (bulletDirectionCFrame * CFrame.Angles(spreadAngle.X, spreadAngle.Y, 0)).LookVector * TRAVEL_DISTANCE
	local bulletRaycast = Workspace:Raycast(muzzlePosition, bulletDirection)
	local bulletIntersection = bulletRaycast and bulletRaycast.Position or viewportPointIntersection
	local distanceToIntersection = (muzzlePosition - bulletIntersection).Magnitude
	
	local part = game.ReplicatedStorage.Part:Clone()
	part.Size = Vector3.new(0.1, 0.1, distanceToIntersection)
	part.CFrame = CFrame.lookAt(bulletIntersection, muzzlePosition) * CFrame.new(0, 0, -distanceToIntersection / 2)
	part.Parent = Workspace
end

To achieve cone-shaped bullet spread, I am using a slightly modified open-sourced function that I found and so far it has been working perfectly, this is the only issue that has happened.

Solved, I should’ve used

local bulletIntersection = bulletRaycast and bulletRaycast.Position or muzzlePosition + bulletDirection

instead of

local bulletIntersection = bulletRaycast and bulletRaycast.Position or viewportPointIntersection

This caused it to use the viewport raycast, which was just a raycast that poined to where my mouse was at with no offsets.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.