How can I move a direction off by an angle

Hi. I am making a game and I’ve run into an issue. I am making guns and I need the bullet to not be 100% accurate. Right now I just have a basic script to get where the player shot:

-- ... 
local hit_pos = m.hit.p
local ray = Ray.new(p.Character.Head.Position, (hit_pos - p.Character.Head.Position).unit * 300)
-- ...

How can I move the direction the ray goes by an angle?

I found this code from Help with spread in raycasting

local cos = math.cos
local sin = math.sin
local rnd = math.random

local up = Vector3.new(0, 1, 0)
local spread = 1/100 -- +-1 stud precision per 100 studs distance

local function newDir(dir)
  dir = dir.Unit

  local angle = rnd() * math.pi * 2
  local axisA = up:Cross(dir)
  local axisB = dir:Cross(axisA)

  return dir + spread * (cos(angle) * axisA + sin(angle) * axisB)
end
1 Like