Created
December 5, 2015 10:07
-
-
Save Elmuti/b1d37f2b5784be76a683 to your computer and use it in GitHub Desktop.
/System/Classes/Vector2
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 | |
function Vector2.New(x, y) | |
local vec2 = {} | |
setmetatable(vec2, Vector2) | |
vec2.x = x or 0 | |
vec2.y = y or 0 | |
return vec2 | |
end | |
--Fires when you index a Vector2 property | |
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 | |
local normVec = Vector2.New() | |
normVec.x = x / len | |
normVec.y = y / len | |
return normVec | |
end | |
return rawget(self, index) | |
end | |
--Returns Vector2 translated (slid) by Vector2 | |
function Vector2.__add(lhs, rhs) | |
return Vector2.New(lhs.x + rhs.x, lhs.y + rhs.y) | |
end | |
--returns Vector2 with each component multiplied by corresponding component | |
function Vector2.__mul(lhs, rhs) | |
return Vector2.New(lhs.x * rhs.x, lhs.y * rhs.y) | |
end | |
--returns Vector2 with each component divided by corresponding component | |
function Vector2.__div(lhs, rhs) | |
return Vector2.New(lhs.x / rhs.x, lhs.y / rhs.y) | |
end | |
--returns Vector2 translated (slid) by -Vector2 (also gives relative position of 1 to the other) | |
function Vector2.__sub(lhs, rhs) | |
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