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(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.