summaryrefslogtreecommitdiff
path: root/math.lua
diff options
context:
space:
mode:
authorElizabeth Alexander Hunt <me@liz.coffee>2026-04-22 15:58:41 -0700
committerElizabeth Alexander Hunt <me@liz.coffee>2026-04-22 15:58:41 -0700
commit078eca583eec21d317e931c84db8f084bef4305d (patch)
tree76b303cdda70a87a5febaf57726d4f8779a387a3 /math.lua
parent3555b9ff88c3872c8f2dd8a8ab02382e2a7d0cb2 (diff)
downloaddyl8-078eca583eec21d317e931c84db8f084bef4305d.tar.gz
dyl8-078eca583eec21d317e931c84db8f084bef4305d.zip
Snapshot
Diffstat (limited to 'math.lua')
-rw-r--r--math.lua36
1 files changed, 36 insertions, 0 deletions
diff --git a/math.lua b/math.lua
new file mode 100644
index 0000000..f745dc8
--- /dev/null
+++ b/math.lua
@@ -0,0 +1,36 @@
+Vec2 = {}
+Vec2.__index = Vec2
+Vec2.__add = function(a, b) return vec2(a.x + b.x, a.y + b.y) end
+Vec2.__unm = function(a) return vec2(-a.x, -a.y) end
+Vec2.__sub = function(a, b) return a + (-b) end
+Vec2.__mul = function(a, b)
+ if (type(b) == "number") then return vec2(a.x * b, a.y * b) end
+ return a.x * b.x + a.y * b.y
+end
+Vec2.__div = function(a, b) return vec2(a.x / b.x, a.y / b.y) end
+Vec2.__tostring = function(a) return "(" .. a.x .. "," .. a.y .. ")" end
+
+function Vec2:magnitude()
+ return sqrt(self.x * self.x + self.y * self.y)
+end
+
+function Vec2:normal()
+ local m = self:magnitude()
+ if m == 0 then return vec2(self.x, self.y) end
+ return vec2(self.x / m, self.y / m)
+end
+
+function Vec2:apply(f)
+ return vec2(f(self.x), f(self.y))
+end
+
+function vec2(x, y)
+ if type(x) == "table" then return vec2(x.x, x.y) end
+ return setmetatable({ x = x, y = y }, Vec2)
+end
+
+function normalize_scalar(x)
+ if x == 0 then return 0 end
+ if x < 0 then return -1 end
+ return 1
+end \ No newline at end of file