Skip to content

Instantly share code, notes, and snippets.

@Elmuti
Created December 14, 2015 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Elmuti/a26cdf288752698a58d0 to your computer and use it in GitHub Desktop.
Save Elmuti/a26cdf288752698a58d0 to your computer and use it in GitHub Desktop.
Orakel/src/System/Classes/Vector2
local Vector2 = {}
local std = require("System/StdLib")
local sqrt = math.sqrt
function Vector2.new(x, y)
assert(tonumber(x) or (x == nil), std.err("Vector2 coordinates can only be numbers"))
assert(tonumber(x) or (x == nil), std.err("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.__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:ScreenCoordinates()
local wx = self.x
local wy = self.y
end
function Vector2.__tostring(self)
return self.x..", "..self.y
end
function Vector2.__eq(lhs, rhs)
assert(rhs.Type == "Vector2", std.err("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