Vector2.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Island.StandardLib.Math
  6. {
  7. public struct Vector2
  8. {
  9. public float X { get; set; }
  10. public float Y { get; set; }
  11. public static Vector2 Zero = new Vector2(0, 0);
  12. public Vector2(float x, float y)
  13. {
  14. X = x;
  15. Y = y;
  16. }
  17. /// <summary>
  18. /// 使用通信数据初始化
  19. /// </summary>
  20. /// <param name="xyz">X:Y:Z</param>
  21. public Vector2(string xy)
  22. {
  23. string[] l = xy.Split(':');
  24. if (l.Length == 2)
  25. {
  26. if (float.TryParse(l[0], out float x) &&
  27. float.TryParse(l[1], out float y))
  28. {
  29. X = x;
  30. Y = y;
  31. }
  32. else
  33. {
  34. X = Y = 0;
  35. }
  36. }
  37. else X = Y = 0;
  38. }
  39. /// <summary>
  40. /// 提升维度
  41. /// </summary>
  42. /// <param name="y">初始高度</param>
  43. /// <returns></returns>
  44. public Vector3 UpperXZ(float y)
  45. {
  46. return new Vector3(X, y, Y);
  47. }
  48. /// <summary>
  49. /// 向量加法
  50. /// </summary>
  51. /// <param name="vec"></param>
  52. /// <returns></returns>
  53. public Vector2 ADD(Vector2 vec)
  54. {
  55. return new Vector2(X + vec.X, Y + vec.Y);
  56. }
  57. /// <summary>
  58. /// 向量减法
  59. /// </summary>
  60. /// <param name="vec"></param>
  61. /// <returns></returns>
  62. public Vector2 RED(Vector2 vec)
  63. {
  64. return new Vector2(X - vec.X, Y - vec.Y);
  65. }
  66. /// <summary>
  67. /// 如果向量表示点的坐标,计算这个点和指定参数点之间的距离
  68. /// </summary>
  69. /// <param name="vec">指定点</param>
  70. /// <returns></returns>
  71. public float DistanceOf(Vector2 vec)
  72. {
  73. float x1 = (float)System.Math.Pow(X - vec.X, 2);
  74. float x2 = (float)System.Math.Pow(Y - vec.Y, 2);
  75. return (float)System.Math.Pow(x1 + x2, 0.5d);
  76. }
  77. public string ToXY()
  78. {
  79. return X + ":" + Y;
  80. }
  81. public override string ToString()
  82. {
  83. return "(" + X + ", " + Y + ")";
  84. }
  85. public override bool Equals(object obj)
  86. {
  87. if (!(obj is Vector2)) return false;
  88. Vector2 v2 = (Vector2)obj;
  89. return X == v2.X && Y == v2.Y;
  90. }
  91. public override int GetHashCode()
  92. {
  93. return X.GetHashCode() ^ Y.GetHashCode();
  94. }
  95. public static bool operator ==(Vector2 a, Vector2 b)
  96. {
  97. return a.Equals(b);
  98. }
  99. public static bool operator !=(Vector2 a, Vector2 b)
  100. {
  101. return !a.Equals(b);
  102. }
  103. }
  104. }