How to create a laser gun

I want to create a laser gun that fires a projectile towards the players mouse. I’ve thought of using raycasts or just straight up cloning the projectile and adding velocity to it

1 Like

For a laser gun, I think raycasting might be your best bet. After raycasting, you could just use a part for the visual effect of the shot. Let me know if you need some example code.

1 Like

That would be super useful! Thank you very much

1 Like

Assuming you use a tool for your laser gun, you could do something like this:

In a local script within the tool you could have the following:

local tool = script.Parent
local remote = tool:WaitForChild("RemoteEvent")
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

tool.Activated:Connect(function()
	-- When tool is activated fire the remote event with information about where the player is aiming
	remote:FireServer(mouse.Hit.Position)
end)

In a server script (that’s also in the tool) you could then have the following:

local tool = script.Parent
local remote = tool.RemoteEvent

remote.OnServerEvent:Connect(function(player, mouseTarget)
	
	-- set up raycasting parameters   
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {player.Character} --ignore the character when raycasting
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	
	--raycast towards whatever the player's mouse is aiming at 
	local startPos = player.Character.PrimaryPart.Position
	local range = 300 -- how far the raycast can travel 
	local aimDirection = (mouseTarget - startPos).unit * range
	local rayResult = workspace:Raycast(startPos, aimDirection, raycastParams) -- raycast! 
	
	if rayResult then
		local hitPart = rayResult.Instance -- the part the raycast hit 
		local hitPos = rayResult.Position -- the position where the raycast hit 
		local distance = (hitPos - startPos).magnitude -- distance of our shot 
		
		if hitPart then
			--Here you can check if the part that got hit parent for a humanoid
			-- and do damage based on that
		end
			
		-- set up the laser part which just acts as a visual effect 
		local laserPart = Instance.new("Part")
		laserPart.Anchored = true 
		laserPart.Name = "Laser"
		laserPart.BrickColor = BrickColor.new("Really red")
		laserPart.CanCollide = false
		laserPart.Size = Vector3.new(0.2, 0.2, distance)
		laserPart.CFrame = CFrame.new(tool.Handle.Position, hitPos) * CFrame.new(0, 0, -distance / 2)
		laserPart.Parent = workspace
		
		wait(0.2)
		laserPart:Destroy()
	end
end)

Feel free to let me know if I need to explain something better, hope this helps!

4 Likes

Thank you for the code but I am wondering if there is a way to make it where it launches a projectile cloned from serverstorage like an energy orb or something. Would I just tween it from the guns psoition to the raycast reults position?

Yes. You can clone the projectile and then set it’s position to gun position, then fire it.

2 Likes