Skip to content

Instantly share code, notes, and snippets.

@estama
Last active June 21, 2020 10:42
Show Gist options
  • Select an option

  • Save estama/839e9ff0a7b5d8647cf2255032e253d3 to your computer and use it in GitHub Desktop.

Select an option

Save estama/839e9ff0a7b5d8647cf2255032e253d3 to your computer and use it in GitHub Desktop.
function randomPointInSphere(radius)
radius = radius or 1
local sx, sy, sz = 0, 0, 0;
for i = 1, 4 do
local x, y, z = math.random(), math.random(), math.random()
sx, sy, sz = sx + x, sy + y, sz + z
local xc, yc, zc = x - 0.5, y - 0.5, z - 0.5
if xc * xc + yc * yc + zc * zc <= 0.25 then
local r2 = radius * 2
return xc * r2, yc * r2, zc * r2
end
end
sx, sy, sz = sx - 2, sy - 2, sz - 2
local u = math.random()
local norm = math.sqrt(0.5 * (math.sqrt(u) + u)/(sx*sx + sy*sy + sz*sz + 1e-25)) * radius
return sx*norm, sy*norm, sz*norm
end
function randomPointInCircle(radius)
radius = radius or 1
local sx, sy = 0, 0
for i = 1, 4 do
local x, y = math.random(), math.random()
sx, sy = sx + x, sy + y
local xc, yc = x - 0.5, y - 0.5
if xc * xc + yc * yc <= 0.25 then
local r2 = radius * 2
return xc * r2, yc * r2
end
end
sx, sy = sx - 2, sy - 2
local norm = math.sqrt(math.random()/(sx*sx+sy*sy + 1e-25)) * radius
return sx*norm, sy*norm
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment