Skip to content

Instantly share code, notes, and snippets.

@dotxnc
Created February 17, 2017 08:55
Show Gist options
  • Save dotxnc/8f2b58f8e3d84b306076934311565fe7 to your computer and use it in GitHub Desktop.
Save dotxnc/8f2b58f8e3d84b306076934311565fe7 to your computer and use it in GitHub Desktop.
vector math as a lua object
local vector = {x,y,z}
vector.__index = vector
vector.__add = function(lhs, rhs)
if rhs == nil then return lhs end
local _n = vector(0,0,0)
if type(rhs) == "number" then rhs = vector(rhs,rhs,rhs) end
_n.x = lhs.x + rhs.x
_n.y = lhs.y + rhs.y
_n.z = lhs.z + rhs.z
return _n
end
vector.__sub = function(lhs, rhs)
if rhs == nil then return lhs end
local _n = vector(0,0,0)
if type(rhs) == "number" then rhs = vector(rhs,rhs,rhs) end
_n.x = lhs.x - rhs.x
_n.y = lhs.y - rhs.y
_n.z = lhs.z - rhs.z
return _n
end
vector.__mul = function(lhs, rhs)
if rhs == nil then return lhs end
local _n = vector(0,0,0)
if type(rhs) == "number" then rhs = vector(rhs,rhs,rhs) end
_n.x = lhs.x * rhs.x
_n.y = lhs.y * rhs.y
_n.z = lhs.z * rhs.z
return _n
end
vector.__div = function(lhs, rhs)
if rhs == nil then return lhs end
local _n = vector(0,0,0)
if type(rhs) == "number" then rhs = vector(rhs,rhs,rhs) end
_n.x = lhs.x / rhs.x
_n.y = lhs.y / rhs.y
_n.z = lhs.z / rhs.z
return _n
end
setmetatable(vector, {
__call = function(cls, ...)
return cls.new(...)
end
})
function vector.new(x,y,z)
self = setmetatable({}, vector)
self.x = x or 0
self.y = y or 0
self.z = z or 0
return self
end
function vector:dist(target)
return math.sqrt(math.pow(self.x-target.x,2) + math.pow(self.y-target.y,2))
end
function vector:copy()
return vector(self.x, self.y, self.z)
end
function vector:length()
return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z)
end
function vector:normalize()
local len = self:length()
self.x = self.x/len
self.y = self.y/len
self.z = self.z/len
end
function rvec()
local angle = math.rad(math.random(360))
local vec = vector(math.cos(angle), math.sin(angle), 0)
return vec
end
--- port of the processing map function
function map(v, a1, a2, b1, b2)
return b1 + (b2-b1) * ((v-a1) / (a2 - a1))
end
return vector
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment