Vector3: add unit / normalise

This commit is contained in:
Starbeamrainbowlabs 2021-06-26 16:56:26 +01:00
parent c76a049286
commit 0a3680aa7d
Signed by: sbrl
GPG key ID: 1BE5172E637709C2
2 changed files with 49 additions and 0 deletions

View file

@ -0,0 +1,37 @@
local Vector3 = require("worldeditadditions.utils.vector3")
-- To find these numbers, in Javascript:
-- function t(x) { return Math.sqrt((x*x)*3); }
-- for(let i = 0; i < 1000000000; i++) { let r = t(i); if(Math.floor(r) === r) console.log(`i ${i}, r ${r}`); }
describe("Vector3.unit", function()
it("should work with a positive vector", function()
local a = Vector3.new(10, 10, 10)
assert.are.same(
Vector3.new(57735, 57735, 57735),
a:unit():multiply(100000):floor()
)
end)
it("should work with a the normalise alias", function()
local a = Vector3.new(10, 10, 10)
assert.are.same(
Vector3.new(57735, 57735, 57735),
a:normalise():multiply(100000):floor()
)
end)
it("should work with a negative vector", function()
local a = Vector3.new(10, 10, 10)
assert.are.same(
Vector3.new(57735, 57735, 57735),
a:unit():multiply(100000):floor()
)
end)
it("should work with a mixed vector", function()
local a = Vector3.new(-371635731, 371635731, -371635731)
assert.are.same(
Vector3.new(-57736, 57735, -57736),
a:unit():multiply(100000):floor()
)
end)
end)

View file

@ -208,6 +208,18 @@ function Vector3.set_to(a, length)
return (a / a:length()) * length
end
--- Returns the unit vector of this vector.
-- The unit vector is a vector with a length of 1.
-- Returns a new vector.
-- Does not change the direction of the vector.
-- @param a Vector3 The vector to operate on.
-- @returns Vector3 The unit vector of this vector.
function Vector3.unit(a)
return a / a:length()
end
--- Alias of Vector3.unit.
function Vector3.normalise(a) return a:unit() end
--- Return a vector that is amount distance towards b from a.
-- @param a Vector3 The vector to move from.