vec3.lua 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. Vec3 = {
  2. new = function(x, y, z)
  3. local instance = { x, y, z }
  4. setmetatable(instance, Vec3)
  5. return instance
  6. end,
  7. magnitude = function(self)
  8. return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
  9. end,
  10. __index = function(table, index)
  11. if index == 'x' then
  12. return rawget(table, 1)
  13. elseif index == 'y' then
  14. return rawget(table, 2)
  15. elseif index == 'z' then
  16. return rawget(table, 3)
  17. else
  18. error('vec3 key must be x, y or z')
  19. end
  20. end,
  21. __newindex = function(table, index, value)
  22. if index == 'x' then
  23. return rawset(table, 1, value)
  24. elseif index == 'y' then
  25. return rawset(table, 2, value)
  26. elseif index == 'z' then
  27. return rawset(table, 3, value)
  28. else
  29. error('vec3 key must be x, y or z')
  30. end
  31. end,
  32. __add = function(a, b)
  33. return Vec3.new(a.x + b.x, a.y + b.y, a.z + b.z)
  34. end,
  35. __sub = function(a, b)
  36. return Vec3.new(a.x - b.x, a.y - b.y, a.z - b.z)
  37. end,
  38. __unm = function(a)
  39. return Vec3.new(-a.x, -a.y, -a.z)
  40. end,
  41. __eq = function(a, b)
  42. return a.x == b.y and a.y == b.y and a.z == b.z
  43. end,
  44. __tostring = function(self)
  45. return '(' .. self.x .. ',' .. self.y .. ',' .. self.z .. ')'
  46. end
  47. }
  48. local a = Vec3.new(1, 1, 1)
  49. local b = Vec3.new(1, 1, 1)