How to make a bullet using raycasting

I made this gun using raycasting and it creates a long laser to wherever your mouse is pointing. But I want just a small bullet that shoots in the direction of where you shot and not one that infinitely goes on. Here’s my ServerScript:

-- Variables
local tool = script.Parent
local damageEvent = tool:WaitForChild("Damage")
local firedEvent = tool:WaitForChild("Fired")
local config = require(script.Parent:WaitForChild("Configurations"))
local fireRate = config.fireRate
local damage = config.damage
local spread = config.spread
local range = config.range

local handle = tool.Handle
local debounce = true

-- Ray Cast
firedEvent.OnServerEvent:Connect(function(player, toP, fromP, mouse)
	local direction = range * (toP - fromP).Unit
	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	raycastParams.FilterDescendantsInstances = {handle, game.Workspace.Lasers}
	raycastParams.IgnoreWater = false
	
	local result = workspace:Raycast(fromP, direction, raycastParams)	
	
	local midPoint = fromP + direction /2

	local laser = Instance.new("Part")
	laser.Parent = game.Workspace.Lasers
	laser.Anchored = true
	laser.CanCollide = false
	laser.Locked = true
	laser.BrickColor = BrickColor.new("Bright yellow")
	laser.Material = Enum.Material.Plastic

	local random = Vector3.new(math.random(-spread, spread), math.random(-spread, spread), math.random(-spread, spread))

	laser.CFrame = CFrame.new(midPoint, fromP) + random/1000
	laser.Size = Vector3.new(.075, .075, direction.magnitude)
	
	for i = 1, 10 do
		wait(.025)
		laser.Transparency = laser.Transparency + .1
	end
	game.Debris:AddItem(laser, config.fireRate)
end)
3 Likes

You can’t make a bullet with raycasting directly. But you can use the raycast results to make a bullet. There are different situations in which you might use different information.

If you want to tween a bullet to the positions, then you would use the initial position, and tween to the RaycastResult.Position.

If you want to use physics, then you might use a bodymover. You could make a part, then give it a bodyvelocity, and make it move a certain direction.

In either case, if you need a direction vector, you can get the direction by doing (endposition - initialposition).Unit. This gives the direction, and if you need to make it a certain magnitude then you multiply.

6 Likes