Want help with raycast gun code

This server portion of this raycast gun script works fine. (A little messy, I know) but it works. Though the main issue is that it doesn’t “hit” enemies up close or deals damage up close. So how could I improve this script to where it can hit and damage enemies up close. (The wait(.3) isn’t the issue, I’ve already tried removing it.)

local event = game.ReplicatedStorage.GunEvents.Bullet
local tool = script.Parent.Parent
function onEvent(player, shotsound, hit, barrel, barrel2, mouse)
	local character = player.Character.Torso
	
	shotsound:Play()
	local bullet = Instance.new("Part")
	bullet.Shape = Enum.PartType.Block
	bullet.Color = Color3.new(1, 1, 0.498039)
	bullet.Material = Enum.Material.Neon
	bullet.Size = Vector3.new(.2,.2,.2)
	bullet.Parent = script.Parent
	bullet.CanCollide = false
	local ray = Ray.new(tool.Barrel.CFrame.p, (hit - tool.Barrel.CFrame.p).unit*300)






	bullet.CFrame = CFrame.new(barrel2, hit)

	local Velocity = Instance.new("BodyVelocity")
	Velocity.maxForce = Vector3.new(math.huge, math.huge, math.huge) 
	Velocity.Velocity = bullet.CFrame.LookVector * 500


	Velocity.Parent = bullet
	wait(.3)
	bullet:Destroy()
	local hit2 = game.Workspace:FindPartOnRay(ray, player.Character)
	if hit2.Parent:FindFirstChild('Humanoid')  and game.Players:GetPlayerFromCharacter(hit2.Parent) == nil then
		local humanoid1 = hit2.Parent:FindFirstChild('Humanoid')
		humanoid1:TakeDamage(20)


	end

	

	bullet.Touched:connect(function(hit) 
		if hit:IsA("Part")  and hit.Parent ~= player.Character and hit.Parent ~= bullet and hit.Parent ~= barrel then
	bullet:Destroy()

		end

	end)
	
	
end



event.OnServerEvent:Connect(onEvent)

1 Like

This is probably because the ray starts at the barrel of the gun. Meaning that in the case where the barrel part is within another player, that part won’t get found on the Ray.

Your options are probably to try checking what parts are touching the barrel at the time of a shot, or to Raycast from the head instead of the gun barrel (which is another common tactic used a lot in Roblox Clans)

Ah ok that makes sense, so make sure the ray isn’t hitting anything such as the weapon itself?