Advertisement
doobbyyus

Vector3 Class

Mar 20th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. local Vector3 = {}
  2. local mt = {__index = Vector3}
  3.  
  4. function Vector3.new(x, y, z)
  5. local self = setmetatable({}, mt)
  6. self.coords = {}
  7. self.coords.x = x or 0
  8. self.coords.y = y or 0
  9. self.coords.z = z or 0
  10. self.magnitude = (self.coords.x^2+self.coords.y^2+self.coords.z^2)^0.5
  11.  
  12. return self
  13. end
  14.  
  15. function mt.__div(a, b)
  16. local at, bt = type(a), type(b)
  17.  
  18. if at == 'table' and bt == 'table' then
  19. return Vector3.new(a.x / b.x, a.y / b.y, a.z / b.z)
  20. elseif at == 'table' and bt == 'number' then
  21. return Vector3.new(a.x / b, a.y / b, a.z / b)
  22. elseif at == 'number' and bt == 'table' then
  23. return Vector3.new(a / b.x, a / b.y, a / b.z)
  24. end
  25. end
  26.  
  27. function mt.__mul(a, b)
  28. local at, bt = type(a), type(b)
  29.  
  30. if at == 'table' and bt == 'table' then
  31. return Vector3.new(a.x * b.x, a.y * b.y, a.z * b.z)
  32. elseif at == 'table' and bt == 'number' then
  33. return Vector3.new(a.x * b, a.y * b, a.z * b)
  34. elseif at == 'number' and bt == 'table' then
  35. return Vector3.new(a * b.x, a * b.y, a * b.z)
  36. end
  37. end
  38.  
  39. function mt.__add(a, b)
  40. return Vector3.new(a.x + b.x, a.y + b.y, a.z + b.z)
  41. end
  42.  
  43. function mt.__sub(a, b)
  44. return Vector3.new(a.x - b.x, a.y - b.y, a.z - b.z)
  45. end
  46.  
  47. function mt:__unm()
  48. return Vector3.new(-self.x, -self.y, -self.z)
  49. end
  50.  
  51. function mt:__eq(v)
  52. return ((self.x == v.x) and (self.y == v.y) and (self.z == v.z))
  53. end
  54.  
  55. function mt:__lt(v)
  56. local isTable = (type(v) == 'table')
  57.  
  58. if isTable then
  59. return (self.magnitude < v.magnitude)
  60. else
  61. return (self.magnitude < v)
  62. end
  63. end
  64.  
  65. function mt:__le(v)
  66. local isTable = (type(v) == 'table')
  67.  
  68. if isTable then
  69. return (self.magnitude <= v.magnitude)
  70. else
  71. return (self.magnitude <= v)
  72. end
  73. end
  74.  
  75. function mt:__index(i)
  76. if rawget(self.coords, i:lower()) then
  77. return rawget(self.coords, i:lower())
  78. elseif rawget(self, i:lower()) then
  79. return rawget(self, i:lower())
  80. elseif i:lower() == 'unit' then
  81. return self / self.magnitude
  82. end
  83. end
  84.  
  85. function mt:__tostring()
  86. return self.x .. ', ' .. self.y .. ', ' .. self.z
  87. end
  88.  
  89. function Vector3:Lerp(b, a)
  90. return self + (b - self) * a
  91. end
  92.  
  93. local a = Vector3.new(6, 4, 2)
  94. local b = Vector3.new(3, 2, 1)
  95.  
  96. print(a:Lerp())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement