Builtin: Add vector.angle(). Returns the angle between 2 vectors (#7738)
authorANAND <ClobberXD@gmail.com>
Sun, 17 Mar 2019 02:05:03 +0000 (07:35 +0530)
committerParamat <paramat@users.noreply.github.com>
Sun, 17 Mar 2019 02:05:03 +0000 (02:05 +0000)
builtin/common/vector.lua
doc/lua_api.txt

index c3d380ed34d69a723be4cf31c9cfa841b74c0622..9a53409fa0f7a44347674cfbf74a30e5817ef81a 100644 (file)
@@ -70,6 +70,15 @@ function vector.direction(pos1, pos2)
        })
 end
 
+function vector.angle(a, b)
+       local dotp = a.x * b.x + a.y * b.y + a.z * b.z
+       local cpx = a.y * b.z - a.z * b.y
+       local cpy = a.z * b.x - a.x * b.z
+       local cpz = a.x * b.y - a.y * b.x
+       local crossplen = math.sqrt(cpx ^ 2 + cpy ^ 2 + cpz ^ 2)
+       return math.atan2(crossplen, dotp)
+end
+
 function vector.add(a, b)
        if type(b) == "table" then
                return {x = a.x + b.x,
index 39e0a848d2686674d959df95f4afc81a73f7e73f..899c0abdbbc6893d3f9214f2ae777bfa9a2147d9 100644 (file)
@@ -2399,6 +2399,8 @@ For the following functions, `v`, `v1`, `v2` are vectors,
     * Returns a boolean, `true` if the vectors are identical.
 * `vector.sort(v1, v2)`:
     * Returns in order minp, maxp vectors of the cuboid defined by `v1`, `v2`.
+* `vector.angle(v1, v2)`:
+    * Returns the angle between `v1` and `v2` in radians.
 
 For the following functions `x` can be either a vector or a number: