I’ve been searching for a way how to fix this all day, i’m going to try my best to explain what is going on.
So I’ve made a gun that shoots a bullet, it works fine when shooting at the sky + when shooting at a part. I decided to give the bullets a spread so they don’t go right to your mouse.
The bullet spread works perfectly fine when shooting at a part but when shooting at the sky it has offset issues, the bullet trace doesn’t connect to the gun and starts going all over the place.
Here is my code: ```
local ray = Ray.new(gun.Point.CFrame.p, (mouse.Hit.p - gun.Point.CFrame.p).unit * 600)
local part, position = game.Workspace:FindPartOnRay(ray, player.Character, false, true)
local beam = Instance.new("Part", workspace)
beam.BrickColor = BrickColor.new("Bright yellow")
beam.FormFactor = "Custom"
beam.Material = "Neon"
beam.Transparency = 0
beam.Anchored = true
beam.Locked = true
beam.CanCollide = false
local distance = (gun.Point.CFrame.p - position).magnitude
beam.Size = Vector3.new(0.1, 0.1, distance)
local Spread = 1.25
local Direction = (CFrame.new(gun.Point.CFrame.p,mouse.Hit.p) * CFrame.new(0, 0, -distance / 2) * CFrame.Angles(math.rad(-Spread+(math.random()*(Spread*2))),math.rad(-Spread+(math.random()*(Spread*2))),0))
beam.CFrame = Direction
game:GetService("Debris"):AddItem(beam, 0.1)```
When you defined Direction, you used mouse.Hit.p for the end position of the CFrame instead of the position from the raycast. This causes the weird offset because mouse.Hit.p isn’t the same as the returned position from the raycast and you used position to get the distance instead of mouse.Hit.p. Change: CFrame.new(gun.Point.CFrame.p,mouse.Hit.p) to CFrame.new(gun.Point.CFrame.p,position)
After testing Fezezen’s solution I found that it didn’t work, even without fake spread. This issue has been around forever and I don’t think there’s a fix on the devforum.
Basically I think it’s because the bullet doesn’t have enough “range” to actually get to the place where the mouse’s world position is.
This is the code I use for raycasting in this video
local p = self.head.Position
local x = random(0,1)
if x == 0 then
x = -1
end
local y = random(0,1)
if y == 0 then
y = -1
end
local dir = CF(p,self.mouse.Hit.p) * CFAngles(rad(random()*self.spread*x),rad(random()*self.spread*y),0)
local ray = raynew(p,dir.lookVector*999)
local hit,pos,normal = raycast(workspace,ray,{self.character})
local beam = b:Clone()
local dis = (self.muzzle.Position-pos).Magnitude
beam.CFrame = CF(self.muzzle.Position,pos)*CF(0,0,-dis/2)
beam.Size = Vec3(.05,.05,dis)
beam.Parent = self.model
game.Debris:AddItem(beam,.1)