From 59c12c768a79a93c7b9d8886b0b6d0f68b4b9d59 Mon Sep 17 00:00:00 2001 From: ANAND Date: Sun, 17 Mar 2019 07:35:03 +0530 Subject: [PATCH] Builtin: Add vector.angle(). Returns the angle between 2 vectors (#7738) --- builtin/common/vector.lua | 8 ++++++++ doc/lua_api.txt | 34 ++++++++++++++++++++++++---------- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/builtin/common/vector.lua b/builtin/common/vector.lua index 0549f9a56..47b44dc68 100644 --- a/builtin/common/vector.lua +++ b/builtin/common/vector.lua @@ -90,6 +90,14 @@ function vector.direction(pos1, pos2) return {x=x_raw, y=y_raw, z=z_raw} 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 diff --git a/doc/lua_api.txt b/doc/lua_api.txt index c3b05bb8c..1dd02cb79 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -2202,16 +2202,30 @@ Spatial Vectors --------------- * `vector.new(a[, b, c])`: returns a vector: * A copy of `a` if `a` is a vector. - * `{x = a, y = b, z = c}`, if all `a, b, c` are defined -* `vector.direction(p1, p2)`: returns a vector -* `vector.distance(p1, p2)`: returns a number -* `vector.length(v)`: returns a number -* `vector.normalize(v)`: returns a vector -* `vector.floor(v)`: returns a vector, each dimension rounded down -* `vector.round(v)`: returns a vector, each dimension rounded to nearest int -* `vector.apply(v, func)`: returns a vector -* `vector.equals(v1, v2)`: returns a boolean -* `vector.sort(v1, v2)`: returns minp, maxp vectors of the cuboid defined by v1 and v2 + * `{x = a, y = b, z = c}`, if all of `a`, `b`, `c` are defined numbers. +* `vector.direction(p1, p2)`: + * Returns a vector of length 1 with direction `p1` to `p2`. + * If `p1` and `p2` are identical, returns `{x = 0, y = 0, z = 0}`. +* `vector.distance(p1, p2)`: + * Returns zero or a positive number, the distance between `p1` and `p2`. +* `vector.length(v)`: + * Returns zero or a positive number, the length of vector `v`. +* `vector.normalize(v)`: + * Returns a vector of length 1 with direction of vector `v`. + * If `v` has zero length, returns `{x = 0, y = 0, z = 0}`. +* `vector.floor(v)`: + * Returns a vector, each dimension rounded down. +* `vector.round(v)`: + * Returns a vector, each dimension rounded to nearest integer. +* `vector.apply(v, func)`: + * Returns a vector where the function `func` has been applied to each + component. +* `vector.equals(v1, v2)`: + * 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: