You need the camera's properties for the following formula, mainly the angles of the camera, the position of the camera, vertical FOV, the aspect ratio (width / height), the near and the far clipping plane's distance.
Getting an angle that's inside the camera's view is very simple, you just use the vertical FOV, get a random value between 0 and it (I refer to this as yAngle), then calculate the horizontal FOV (vertical FOV * aspect ratio), create a random value between 0 and that too (this'll be xAngle), then you add the camera's rotation around the y axis (yaw) to the horizontal angle, and the camera's rotation around the x axis (pitch) to the vertical angle (these are xTotal and yTotal respectively).
Now you have the angles. You need to get the distance between the object and the camera. This should be a random value between the near and far value. Lastly, you need to create a vector out of this. There are multiple ways this can be done. You can either use this formula, or you can create a vector pointing in the negative z direction, then create a rotation matrix (the 2 methods do the same, the first one is just the algorithm version of the latter one).
After you got the vector, you can add it to the position of the camera and done, you get a position in the field of view of the camera.
Pseudo-code:
func getPosition(float FOV, float aspect, float cameraXAngle, float cameraYAngle, float near, float far, vec3 cameraPos) {
xTotal := rand(0, FOV * aspect) + cameraXAngle
yTotal := rand(0, FOV) + cameraYAngle
distance := rand(near, far)
vec3 direction = vec3(
distance * cos(xTotal) * sin(yTotal),
distance * cos(xTotal) * cos(yTotal),
distance * sin(xTotal)
)
return cameraPos + direction
}