How can i add spread to this?

I want to add spread to my guns but i don’t know how to add it, can someone help me?

This is my code for calculating variables for the raycast

   	local Origin = FirePointObject.WorldPosition

  local Direction = (direction-Origin).Unit * Settings.MAX_DIST
	local Raycast = workspace:Raycast(Origin, Direction)
	
	local result = Raycast or {Position = Origin+Direction}

Add more raycasts, and give them each a small offset orientation.

I already have something to make more raycasts, the question is how to give it an offset? (spread)

Check if this works out for you:

-- Create a random number generator
local rng = Random.new()

-- Define the minimum and maximum angles of the spread
local minSpread = 0
local maxSpread = 6

-- Specify the initial direction vector (CHANGE THIS TO YOUR OWN CODE)
local direction = Vector3.new(1, 0, 0)

-- Apply a random rotation around the z-axis and a random spread around the direction vector
local rotation = CFrame.Angles(0, 0, rng:NextNumber(0, 2*math.pi))
local spread = CFrame.fromAxisAngle(direction, math.rad(rng:NextNumber(minSpread, maxSpread)))

-- Apply the rotation and spread to the direction vector
direction = direction + (rotation * spread).LookVector -- OP's solution
1 Like

The gun now shoots to the middle of the map, also i forgot to add that the “direction” variable that i have is the mouse.hit.position.

Update: i fixed it myself by chaging

  direction = (rotation * spread).LookVector

To:

   direction = direction + (rotation * spread).LookVector
1 Like

Hey!

I’m glad you made it work. I had to go yesterday and that’s why I didn’t answer.

I’ll update the code provided above with your solution, that way we can help other people too.

1 Like

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