Need help fixing issues with my gun

My first raycast gun is almost finished, i just need some fixes that i cant seem to figure out.
The biggest issue that i have is that the gun deals damage even though the bullet didn’t hit them, it seems to only damage the target when you click on the player, but if i move my mouse off the player it doesnt do damage anymore even when the bullets are hitting the player. https://gyazo.com/94757347532eebdec09daa63c412377e

Another issue that i have is that when you move and shoot, the bullet kind of just lags behind you and its very unrealistic.
here is what i mean: https://gyazo.com/31dad4b59d1d9d2469103369c4d7b58a

Here is my code:

local Spread = script.Parent.Spread.Value
local Gun = script.Parent
script.Parent.BulletRegister.OnServerEvent:Connect(function(player,mouse,Damage)
			script.Parent.Point.Shoot:Play()
		local ray = Ray.new(Gun.Point.CFrame.p, (mouse.p - Gun.Point.CFrame.p).unit * 600)
		local part, position = game.Workspace:FindPartOnRay(ray,player.Character, false, true)
		
		local beam = Instance.new("Part")
			beam.BrickColor = BrickColor.new("Bright yellow")
			beam.FormFactor = "Custom"
			beam.Material = Enum.Material.SmoothPlastic
			beam.Transparency = 0
			beam.Anchored = true
			beam.Locked = true
			beam.CastShadow = false
			beam.CanCollide = false
			
		local distance = (script.Parent.Point.CFrame.p - position).Magnitude
			beam.Size = Vector3.new(0.25, 0.25, distance)
		local Direction = (CFrame.new(script.Parent.Point.CFrame.p,position) * CFrame.Angles(math.rad(-Spread+(math.random()*(Spread*2))),math.rad(-Spread+(math.random()*(Spread*2))),0)   * CFrame.new(0, 0, -distance / 2))
			beam.CFrame = Direction
			beam.Parent = workspace
		
		game:GetService("Debris"):AddItem(beam, 0.1)
		if part then
			if part.Parent:FindFirstChild("Humanoid") then
				part.Parent.Humanoid:TakeDamage(Damage)
			end
		end
end)

thank you for your time

1 Like

The issue you seem to having is that you have cast a ray that goes from your Gun’s position to the Mouse’s direction, then what you have done is created a part that goes in a different direction, which isn’t the same direction as the Ray, meaning that whatever the Ray hits will be the target. In order to include bullet spread, you’ll have to add the spread offset to the Ray’s destination and not the beam.

I think the same as Proxus, RayCast and gun’s Beam of gun are separate now. So, don’t make a Spread offset on gun’s Beam, give ReyCast a Spread offset and position Beam to RayCast.

Look at this code. There’s no Spread offset to RayCast.

local ray = Ray.new(Gun.Point.CFrame.p, (mouse.p - Gun.Point.CFrame.p).unit * 600)

Try to add some Spread offset into the local ray.