summaryrefslogtreecommitdiff
path: root/pos.lua
diff options
context:
space:
mode:
Diffstat (limited to 'pos.lua')
-rw-r--r--pos.lua45
1 files changed, 45 insertions, 0 deletions
diff --git a/pos.lua b/pos.lua
new file mode 100644
index 0000000..605ecbd
--- /dev/null
+++ b/pos.lua
@@ -0,0 +1,45 @@
+local class = require'r.class'
+
+local Pos = class()
+function Pos.new(cls)
+ return setmetatable({},cls)
+end
+function Pos.init(self,x,y)
+ self.x = x
+ self.y = y
+ return self
+end
+function Pos.make(cls,...)
+ return cls:new():init(...)
+end
+function Pos.__add(self,other)
+ return Pos:make(self.x+other.x,self.y+other.y)
+end
+function Pos.__sub(self,other)
+ return Pos:make(self.x-other.x,self.y-other.y)
+end
+function Pos.__mul(a,b)
+ if type(a) == "number" then
+ return Pos:make(a*b.x,a*b.y)
+ elseif type(b) == "number" then
+ return Pos:make(a.x*b,a.y*b)
+ else
+ error("can only multiply Pos by scalar")
+ end
+end
+function Pos.__div(a,b)
+ assert(type(b) == "number","can only divide Pos by scalar")
+ return a*(1/b)
+end
+function Pos.__eq(a,b) return a.x==b.x and a.y==b.y end
+function Pos.lensq(self) return self.x^2 + self.y^2 end
+function Pos.len(self) return math.sqrt(self:lensq()) end
+function Pos.norm(self) return self/self:len() end
+function Pos.dot(self,other) return self.x*other.x+self.y*other.y end
+function Pos.__tostring(self)
+ return string.format("(%.2f,%.2f)",self.x,self.y)
+end
+
+return Pos
+
+