mirror of
https://github.com/luanti-org/luanti.git
synced 2025-06-27 16:36:03 +00:00
Add vector.random_direction()
(#14784)
Generate a random vector of unit length. Useful for many mods.
This commit is contained in:
parent
cb0bbea2a5
commit
e6f77b95f3
2 changed files with 14 additions and 0 deletions
|
@ -375,6 +375,18 @@ function vector.in_area(pos, min, max)
|
|||
(pos.z >= min.z) and (pos.z <= max.z)
|
||||
end
|
||||
|
||||
function vector.random_direction()
|
||||
-- Generate a random direction of unit length, via rejection sampling
|
||||
local x, y, z, l2
|
||||
repeat -- expected less than two attempts on average (volume sphere vs. cube)
|
||||
x, y, z = math.random() * 2 - 1, math.random() * 2 - 1, math.random() * 2 - 1
|
||||
l2 = x*x + y*y + z*z
|
||||
until l2 <= 1 and l2 >= 1e-6
|
||||
-- normalize
|
||||
local l = math.sqrt(l2)
|
||||
return fast_new(x/l, y/l, z/l)
|
||||
end
|
||||
|
||||
if rawget(_G, "core") and core.set_read_vector and core.set_push_vector then
|
||||
local function read_vector(v)
|
||||
return v.x, v.y, v.z
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue