How can I get a random position behind the player camera?

Basically the title; probably this image explains it better:

How could I do this? I’m trying to limit a 145 angle behind the camera. I don’t know where to start.

local camera = workspace.Camera.CurrentCamera
local fieldOfView = camera.FieldOfView/2
local distance = math.random(1,50) --[[ distance in magnitude
the position is away from the camera]]
local yAngle = math.random(fieldOfView, 360-fieldOfView) --[[ I believe
this will find an angle that is outside the field of view... I think]]
local xAngle = math.random(fieldOfView, 360-fieldOfView)
local center = camera.CFrame
local angle = CFrame.Angles(math.rad(xAngle),math.rad(yAngle),0)
local offset = center.LookVector * distance
local randomPosition = center * angle * offset -- should be behind the camera

I forgot where the 0 angle is, so you might need to offset the angle variable by -90 but I think this will work.

Thanks so much! I do have a question, distance is how far is the “part spawned” away from the camera position?

yeah, think about it like a radius. the camera is the center and the distance is how far away the position is. The position wont be in the field of view however.

1 Like