How to return a random position within a given radius of a sphere

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SuperBlooper

I am working with an ai for the game I am making in Godot, a 3d one, and as the title suggests I am looking for how to get a random position within a sphere to allow for randomized movement in the game (I have everything else set, I just need to know how to return a randomized point within a certain radius of a node.)

:bust_in_silhouette: Reply From: Thomas Karcher

You could create a vector for a random position on a unit sphere using one of the formulas described here and multiply this with a random scalar ranging from zero to your desired radius. Something like

func get_random_pos_in_sphere (radius : float) -> Vector3:
  var x1 = rand_range (-1, 1)
  var x2 = rand_range (-1, 1)

  while x1*x1 + x2*x2 >= 1:
    x1 = rand_range (-1, 1)
    x2 = rand_range (-1, 1)

  var random_pos_on_unit_sphere = Vector3 (
    2 * x1 * sqrt (1 - x1*x1 - x2*x2),
    2 * x2 * sqrt (1 - x1*x1 - x2*x2),
    1 - 2 * (x1*x1 + x2*x2))

  return random_pos_on_unit_sphere * rand_range (0, radius)

(Using Marsaglias method described in the article.)