How to make a gun with raycast

So I’ve been trying to make a gun with raycast, damage and reload. But all the tutorials I’ve found either only have 2 or 1 of these things. I currently have reload and damage in my gun, but does anyone know how to add raycast on top of that? If you know a tutorial please send me the link. Scripts here:

script.Parent.DealDamage.OnServerEvent:Connect(function(player, Target, Damage)
	Target.Humanoid:TakeDamage(Damage)
end)
local maxammo = 10
local ammo = maxammo
local reloading = false
local plr = game.Players.LocalPlayer
local plrgui = plr:WaitForChild("PlayerGui")
local text = plrgui:WaitForChild("Ammo"):FindFirstChild("AmmoCount")

script.Parent.Equipped:Connect(function(Mouse)
	local function reload()
		reloading = true
		wait(1)
		script.Parent.reload:Play() -- change reloadingsound to what ever your reload sound is named
		ammo = maxammo
		reloading = false
	end

	script.Parent.Activated:Connect(function()
		if ammo > 0 and not reloading then
			ammo = ammo - 1
			script.Parent.gunshot:Play() -- change gunshot to what ever your gun shot sound is named
			if Mouse.Target.Parent:FindFirstChild("Humanoid") then
				script.Parent.DealDamage:FireServer(Mouse.Target.Parent, 50) -- change the 25 to what ever amount of damage you want to deal
			end
		elseif reloading == false then
			reload()
			script.Parent.gunshot:Stop()-- change gunshot to what ever your gun shot sound is named
		end

		while wait() do
			text.Text = (ammo).." / "..maxammo
		end
	end)

	local input = game:GetService("UserInputService")
	input.InputBegan:Connect(function(Key)
		if Key.KeyCode == Enum.KeyCode.R and reloading == false and ammo ~= maxammo then
			reload()
		end
	end)
end)
2 Likes

Here are a few things to add on top of your question.

First, you’re handling everything on the client, which isn’t ideal.
Exploiters could easily loop through all players and fire the DealDamage remote since there are no checks on the server.

As far as raycasts go there are a bunch of tutorials on it, you could edit them to your liking.

2 Likes