Vector2I.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace BansheeEngine
  4. {
  5. [StructLayout(LayoutKind.Sequential)]
  6. public struct Vector2I
  7. {
  8. public int x;
  9. public int y;
  10. public int this[int index]
  11. {
  12. get
  13. {
  14. switch (index)
  15. {
  16. case 0:
  17. return x;
  18. case 1:
  19. return y;
  20. default:
  21. throw new IndexOutOfRangeException("Invalid Vector2I index.");
  22. }
  23. }
  24. set
  25. {
  26. switch (index)
  27. {
  28. case 0:
  29. x = value;
  30. break;
  31. case 1:
  32. y = value;
  33. break;
  34. default:
  35. throw new IndexOutOfRangeException("Invalid Vector2I index.");
  36. }
  37. }
  38. }
  39. public Vector2I(int x, int y)
  40. {
  41. this.x = x;
  42. this.y = y;
  43. }
  44. public float Magnitude
  45. {
  46. get
  47. {
  48. return (float)MathEx.Sqrt(x * x + y * y);
  49. }
  50. }
  51. public float SqrdMagnitude
  52. {
  53. get
  54. {
  55. return (x * x + y * y);
  56. }
  57. }
  58. // Manhattan distance
  59. public static int Distance(Vector2I a, Vector2I b)
  60. {
  61. return Math.Abs(b.x - a.x) + Math.Abs(b.y - a.y);
  62. }
  63. public static Vector2I operator +(Vector2I a, Vector2I b)
  64. {
  65. return new Vector2I(a.x + b.x, a.y + b.y);
  66. }
  67. public static Vector2I operator -(Vector2I a, Vector2I b)
  68. {
  69. return new Vector2I(a.x - b.x, a.y - b.y);
  70. }
  71. public static Vector2I operator -(Vector2I v)
  72. {
  73. return new Vector2I(-v.x, -v.y);
  74. }
  75. public static Vector2I operator *(Vector2I v, int d)
  76. {
  77. return new Vector2I(v.x * d, v.y * d);
  78. }
  79. public static Vector2I operator *(int d, Vector2I v)
  80. {
  81. return new Vector2I(v.x * d, v.y * d);
  82. }
  83. public static Vector2I operator /(Vector2I v, int d)
  84. {
  85. return new Vector2I(v.x / d, v.y / d);
  86. }
  87. public static bool operator ==(Vector2I lhs, Vector2I rhs)
  88. {
  89. return lhs.x == rhs.x && lhs.y == rhs.y;
  90. }
  91. public static bool operator !=(Vector2I lhs, Vector2I rhs)
  92. {
  93. return !(lhs == rhs);
  94. }
  95. public override int GetHashCode()
  96. {
  97. return x.GetHashCode() ^ y.GetHashCode() << 2;
  98. }
  99. public override bool Equals(object other)
  100. {
  101. if (!(other is Vector2I))
  102. return false;
  103. Vector2I vec = (Vector2I)other;
  104. if (x.Equals(vec.x) && y.Equals(vec.y))
  105. return true;
  106. return false;
  107. }
  108. public override string ToString()
  109. {
  110. return "(" + x + ", " + y + ")";
  111. }
  112. }
  113. }