74 lines
1.5 KiB
Lua
74 lines
1.5 KiB
Lua
local inspect = require("inspect/inspect")
|
|
local Object = require("object")
|
|
|
|
local Vector = Object:extend()
|
|
|
|
function Vector:init(x, y)
|
|
Vector.__super.init(self, x, y)
|
|
self.x = x
|
|
self.y = y
|
|
self.angle = math.atan2(self.x, self.y)
|
|
end
|
|
|
|
function Vector:__add(v)
|
|
return self.__class:new(self.x + v.x, self.y + v.y)
|
|
end
|
|
|
|
function Vector:__sub(v)
|
|
return self.__class:new(self.x - v.x, self.y - v.y)
|
|
end
|
|
|
|
function Vector:__mul(obj)
|
|
if getmetatable(obj) == Vector then
|
|
-- dot product
|
|
return self.x*obj.x + self.y*obj.y
|
|
else
|
|
-- scalar product
|
|
return self.__class:new(self.x*obj, self.y*obj)
|
|
end
|
|
end
|
|
|
|
function Vector:__eq(v)
|
|
return self.x == v.x and self.y == v.y
|
|
end
|
|
|
|
function Vector:__lt(v)
|
|
return self.x < v.x and self.y < v.y
|
|
end
|
|
|
|
function Vector:__le(v)
|
|
return self.x <= v.x and self.y <= v.y
|
|
end
|
|
|
|
function Vector:__gt(v)
|
|
return self.x > v.x and self.y > v.y
|
|
end
|
|
|
|
function Vector:__ge(v)
|
|
return self.x >= v.x and self.y >= v.y
|
|
end
|
|
|
|
function Vector:__unm()
|
|
return self.__class:new(-self.x, -self.y)
|
|
end
|
|
|
|
function Vector:__len() -- magnitude
|
|
return math.sqrt(self.x^2 + self.y^2)
|
|
end
|
|
|
|
function Vector:normalize()
|
|
return self.__class:new(self.x/#self, self.y/#self)
|
|
end
|
|
|
|
-- Method to get the clockwise normal of the vector
|
|
function Vector:normal_cw()
|
|
return self.__class:new(self.y, -self.x)
|
|
end
|
|
|
|
-- Method to get the counterclockwise normal of the vector
|
|
function Vector:normal_ccw()
|
|
return self.__class:new(-self.y, self.x)
|
|
end
|
|
|
|
return Vector
|