Help with raycast

This raycast gun only works if a part is within a small radius, please help.

local m = game.Players.LocalPlayer:GetMouse()

function click()
	
	local e = Ray.new(script.Parent.Handle.Position,m.Hit.Position)
	local Hit, Pos, Normal = workspace:FindPartOnRay(e)
	local gunshot = Instance.new("Sound")
	if Hit then
		if Hit.Parent:FindFirstChild("Humanoid") then
			print("shot a humanoid")
		end
	end
	gunshot.Parent = script.Parent.Handle
	gunshot.SoundId = "rbxassetid://1905367471"
	gunshot.Playing=true
	wait(1.224)
	gunshot:Destroy()
end
script.Parent.Activated:Connect(click)

I recommend you use the newer version of raycasting, workspace:RayCast(). I also made some adjustments to your base code to increase efficiency, such as using events instead of wait().

The following code was written on the forum and wasn’t tested in Studio, if you have problems with it let me know!

local m = game.Players.LocalPlayer:GetMouse()

local handle = script.Parent.Handle

local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = {script.Parent}
raycastParams.IgnoreWater = true

local function click()
	local Result = workspace:Raycast(handle.Position, m.Hit.Position*50, raycastParams)

	if Result then
		if Result.Instance.Parent:FindFirstChild("Humanoid") then
			print("shot a humanoid")
		end
	end

    local gunshot = Instance.new("Sound")
	gunshot.Parent = handle
	gunshot.SoundId = "rbxassetid://1905367471"
	gunshot:Play()

	gunshot.Ended:Connect(function()
        gunshot:Destroy()
    end)

end

script.Parent.Activated:Connect(click) 
1 Like

So, Direction is not position where to look tho:

local m = game.Players.LocalPlayer:GetMouse()

function click()
	local direction = (m.Hit.Position-script.Parent.Handle.Position).unit*1000
	
	local e = Ray.new(script.Parent.Handle.Position, direction)
	local Hit, Pos, Normal = workspace:FindPartOnRay(e)
	local gunshot = Instance.new("Sound")
	if Hit then
		if Hit.Parent:FindFirstChild("Humanoid") then
			print("shot a humanoid")
		end
	end
	gunshot.Parent = script.Parent.Handle
	gunshot.SoundId = "rbxassetid://1905367471"
	gunshot.Playing=true
	wait(1.224)
	gunshot:Destroy()
end
script.Parent.Activated:Connect(click)
1 Like