A problem with my gun script

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

I want to fix a bug that has to do with my gun.

  1. What is the issue? Include screenshots / videos if possible!

The issue is that when i shoot another player while that player shoots, sometimes my shot doesn’t work and doesn’t hit the player but that player’s shot works and hits me.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I tried looking for solutions but i couldn’t find any.

Here are some scripts:

local tool = script.Parent
local event = game.ReplicatedStorage.Events.ShootGun
local m = game.Players.LocalPlayer:GetMouse()

local recoil = false
local recoilTime = 0.25


function Shoot(mouse)
	local char = script.Parent.Parent
	local hum = char.Humanoid
	local origin = tool.Handle.aimpoint
	
	if hum:GetState() ~= Enum.HumanoidStateType.Dead then
		if recoil == false then
			event:FireServer(origin.CFrame.Position, mouse.Hit.Position)
			recoil = true
			wait(recoilTime)
			recoil = false
		end
	end
end

tool.Equipped:Connect(function(mouse)
	mouse.Icon = "rbxassetid://425385055"
	mouse.Button1Down:Connect(function()
		Shoot(mouse)
	end)
end)

tool.Unequipped:Connect(function()
	m.Icon = ""
end)

Event Script

local range = 1000
local tool = script.Parent
local gunshot = tool.Handle.gunshot

game.ReplicatedStorage.Events.ShootGun.OnServerEvent:Connect(function(Player, origin, mousehit)
	local RayCast = Ray.new( origin ,(mousehit-origin).unit * range)
	
	local Part,Position,Normal = game.Workspace:FindPartOnRay(RayCast,Player.Character, false,true)
	local Dist = (mousehit-origin).magnitude

	if not Dist then Dist = 100 end

	if Part and Part.Parent:FindFirstChild("Humanoid") then
		Part.Parent.Humanoid:TakeDamage(30)
	end

	gunshot:Stop()
	gunshot:Play()
end)

Thanks.

Try adding a +2 to the range, just in case the ray ends right before it touches the other person.

I also suggest that you use the latest Raycast method: workspace.Raycast.

1 Like

Thanks for suggesting and replying to my problem, though this did not solve it so i had to fix a few things.
Thanks anyway though.