diff options
author | ubq323 <ubq323@ubq323.website> | 2025-02-18 21:15:17 +0000 |
---|---|---|
committer | ubq323 <ubq323@ubq323.website> | 2025-02-18 21:15:17 +0000 |
commit | bcc60fda65fd583a331a0a21c4d47092c95329eb (patch) | |
tree | 397789cf3e5925cb520ea075a3caac6182fbd9d6 | |
parent | f1492b52414b6f2ad6cfff45375c08677feab18c (diff) |
rect
-rw-r--r-- | pos.lua | 1 | ||||
-rw-r--r-- | rect.lua | 65 |
2 files changed, 66 insertions, 0 deletions
@@ -36,6 +36,7 @@ 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.vals(self) return self.x, self.y end function Pos.__tostring(self) return string.format("(%.2f,%.2f)",self.x,self.y) end diff --git a/rect.lua b/rect.lua new file mode 100644 index 0000000..ca87e49 --- /dev/null +++ b/rect.lua @@ -0,0 +1,65 @@ +local class = require'r.class' +local Pos = require'r.pos' +local Rect = class() +function Rect.from_coords(cls, x0, y0, x1, y1) + assert(x0<x1,"x coords interchanged") + assert(y0<y1,"y coords interchanged") + return setmetatable({ + tl=Pos:make(x0,y0), + br=Pos:make(x1,y1), + x0=x0, y0=y0, x1=x1, y1=y1, + w=x1-x0, h=y1-y0, + }, cls) +end +function Rect.from_pos(cls, tl, br) + assert(tl.x<br.x,"x coords interchanged") + assert(tl.y<br.y,"y coords interchanged") + return setmetatable({ + tl=tl, br=br, + x0=tl.x, y0=tl.y, x1=br.x, y1=br.y, + w=br.x-tl.x, h=br.y-tl.y, + }, cls) +end +function Rect.from_xywh(cls, x0,y0, width,hight) + assert(0<width, "nonpositive width") + assert(0<hight, "nonpositive hight") + return setmetatable({ + tl=Pos:make(x0,y0), + br=Pos:make(x0+width,y0+hight), + x0=x0, y0=y0, + x1=x0+width, + y1=y0+hight, + w=width, h=hight, + }, cls) +end +function Rect.from_centre_dims(cls, centre, width, hight) + assert(0<width, "nonpositive width") + assert(0<hight, "nonpositive hight") + local x0,x1 = centre.x-width/2, centre.x+width/2 + local y0,y1 = centre.y-hight/2, centre.y+hight/2 + return setmetatable({ + tl=Pos:make(x0,y0), + br=Pos:make(x1,y1), + x0=x0,y0=y0,x1=x1,y1=y1, + w=width, h=hight, + }, cls) +end + +function Rect.has(self, point) + return self.x0 <= point.x and point.x <= self.x1 + and self.y0 <= point.y and point.y <= self.y1 +end + +function Rect.vals(self) + return self.x0, self.y0, self.w, self.h +end + +function Rect.draw(self, mode) + love.graphics.rectangle(mode or 'line', self:vals()) +end + +function Rect.__tostring(self) + return tostring(self.tl).."\u{25af}"..tostring(self.br) +end + +return Rect |