Created
May 5, 2020 01:18
-
-
Save Elmuti/f330ddc15291e754a7b669dd87220b3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Vector2 = {} | |
local sqrt = math.sqrt | |
local acos = math.acos | |
local abs = math.abs | |
function Vector2.new(x, y) | |
assert(tonumber(x) or (x == nil), "Vector2 coordinates can only be numbers") | |
assert(tonumber(x) or (x == nil), "Vector2 coordinates can only be numbers") | |
local vec2 = {} | |
setmetatable(vec2, Vector2) | |
vec2.X = x or 0 | |
vec2.Y = y or 0 | |
vec2.Type = "Vector2" | |
return vec2 | |
end | |
--[[ | |
function Vector2:new(x,y) | |
return Vector2.new(x,y) | |
end]] | |
function Vector2.__index(self, index) | |
if index == "Magnitude" then | |
local x, y = rawget(self, "X"), rawget(self, "Y") | |
return sqrt(x * x + y * y) | |
elseif index == "Unit" then | |
local x, y = rawget(self, "X"), rawget(self, "Y") | |
local len = sqrt(x * x + y * y) | |
if len == 0 then | |
return self | |
end | |
return Vector2.new(x / len, y / len) | |
end | |
return rawget(Vector2, index) | |
end | |
function Vector2:Dot(other) | |
return self.Y * other.Y + self.X * other.X | |
end | |
function Vector2:AngleBetween(other) | |
return acos(self.Unit:Dot(other.Unit)) | |
end | |
function Vector2:IsParallelWith(other) | |
return abs(self.Unit:Dot(other.Unit)) == 1 | |
end | |
function Vector2:__tostring() | |
return self.X..", "..self.Y | |
end | |
function Vector2.__eq(lhs, rhs) | |
assert(rhs.Type == "Vector2", "Cannot compare Vector2 with "..tostring(rhs)) | |
if lhs.X == rhs.X and lhs.Y == rhs.Y then | |
return true | |
end | |
return false | |
end | |
function Vector2.__add(lhs, rhs) | |
if type(rhs) == "number" then | |
return Vector2.new(lhs.X + rhs, lhs.Y + rhs) | |
end | |
return Vector2.new(lhs.X + rhs.X, lhs.Y + rhs.Y) | |
end | |
function Vector2.__mul(lhs, rhs) | |
if type(rhs) == "number" then | |
return Vector2.new(lhs.X * rhs, lhs.Y * rhs) | |
end | |
return Vector2.new(lhs.X * rhs.X, lhs.Y * rhs.Y) | |
end | |
function Vector2.__div(lhs, rhs) | |
if type(rhs) == "number" then | |
return Vector2.new(lhs.X / rhs, lhs.Y / rhs) | |
end | |
return Vector2.new(lhs.X / rhs.X, lhs.Y / rhs.Y) | |
end | |
function Vector2.__sub(lhs, rhs) | |
if type(rhs) == "number" then | |
return Vector2.new(lhs.X - rhs, lhs.Y - rhs) | |
end | |
return Vector2.new(lhs.X - rhs.X, lhs.Y - rhs.Y) | |
end | |
return Vector2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment