From 7f1c2b8a00ede0659746102762aeb1da487eb6f8 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 | 9 +++++++++ doc/lua_api.txt | 2 ++ 2 files changed, 11 insertions(+) diff --git a/builtin/common/vector.lua b/builtin/common/vector.lua index c3d380ed3..9a53409fa 100644 --- a/builtin/common/vector.lua +++ b/builtin/common/vector.lua @@ -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, diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 39e0a848d..899c0abdb 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -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: -- 2.25.1