Adding random spread to a raycast and then visualizing that racast

ive been trying to add random bullet spread to my gun system, but for the life of me i cannot get it to work.
here is the code in a serverscript

game.ReplicatedStorage.gunshoot.OnServerEvent:Connect(function(Player, TargetLocation, Handles, gundamage, raynge,sprad)
	if Player.Character == nil then -- Make sure their character exists.
		
		return
	end
	if sprad == nil then
		sprad = 0
	end

	Handles.Sound:Play()
	

	local Beam = Instance.new("Part", workspace)
	Beam.Color = Color3.fromRGB(255,255,255)
	Beam.FormFactor = Enum.FormFactor.Custom
	
	
	Beam.Material = "Glass"
	Beam.Anchored = true
	Beam.CanCollide = false
	Beam.CanQuery = false


	-- Math.
	local Distance = ((Handles.Position - TargetLocation).magnitude)
	print( Distance)
	coroutine.wrap(big)(Beam,Distance) --just for the bullet transparency and size
	



	-- Raycasting [Shoot a ray, get wherever it hit]
	local NewRay = RaycastParams.new()
	local RayDirection = (TargetLocation  - Handles.Position)*raynge -- how far you want the ray to travel before stopping.
	
	local direction = (RayDirection)
	print(RayDirection,"and", direction)

	NewRay.FilterDescendantsInstances = {Player.Character}
  
	local Result = workspace:Raycast(Handles.Position, direction, NewRay)
Beam.CFrame = CFrame.new(Handles.Position,Result.Position) * CFrame.new(0, 0, -Distance/2)
	if Result then -- IF we got a result back.
		if Result.Instance then
			-- It actually hit something.
			if Result.Instance.Parent:FindFirstChild("Humanoid") then
				if Result.Instance.Name == "Head" then
					Result.Instance.Parent.Humanoid.Health -= gundamage * 2
				else
					Result.Instance.Parent.Humanoid.Health -= gundamage
					end
			elseif Result.Instance.Parent.Parent:FindFirstChild("Humanoid") then
				if Result.Instance.Name =="Head" then
					
					Result.Instance.Parent.Parent.Humanoid.Health -= gundamage *2
					
					
			else
				Result.Instance.Parent.Parent.Humanoid.Health -= gundamage
				end
			end
				
			end
		end
end)
	if sprad == nil then
		sprad = 0
	end
	local Random = Random.new()
	local Offset = Vector3.new(
		math.random(-sprad,sprad),
		math.random(-sprad,sprad),
		math.random(-sprad,sprad)
	)/100 * .25

	local spreadAngle = math.rad(sprad)
	local randomSpreadAngle = Random:NextNumber() * 2 * math.pi
	local spreadVector = Vector3.new(math.sin(randomSpreadAngle) * spreadAngle, 0, math.cos(randomSpreadAngle) * spreadAngle)
	local rayDirection = (TargetLocation - Handles.Position).Unit + Offset
	rayDirection = rayDirection.Unit
	local finalDirection = rayDirection * raynge
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.