From 078eca583eec21d317e931c84db8f084bef4305d Mon Sep 17 00:00:00 2001 From: Elizabeth Alexander Hunt Date: Wed, 22 Apr 2026 15:58:41 -0700 Subject: Snapshot --- math.lua | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 math.lua (limited to 'math.lua') 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 -- cgit v1.3