Bullet spread not working at max gun range?

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)
5b0b49db2c11502922be4578a271d78688546027_2_400x500

(Results when shooting far)
34c85412c2f5cde06e528239c14f7756bd048497_2_510x500

local random = Random.new()
local function randomPointInEllipse(spreadDegrees: 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(spreadDegrees), math.rad(spreadDegrees))
	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)
	print(spreadAngle.X, spreadAngle.Y)
	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 do my bullet spread, I use a function that generates a cone to get cone-shaped bullet spread.

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 spread offsets added.

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