ZIMMath.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using o0.Geometry2D.Float;
  2. using System;
  3. using UnityEngine;
  4. namespace ZIM.Unity
  5. {
  6. public static partial class ZIMMath
  7. {
  8. // 向量与x轴的夹角,返回0-360度
  9. public static float DegreeToXAxis(this Vector v)
  10. {
  11. //var a = v.x > 0 ? Math.Atan(v.y / v.x) * 180 / Math.PI : 180 + Math.Atan(v.y / v.x) * 180 / Math.PI;
  12. var a = Math.Atan2(v.y, v.x) * 180 / Math.PI;
  13. if (a < 0)
  14. a += 360;
  15. return (float)a;
  16. }
  17. // Projects a vector onto another vector.
  18. public static Vector2 Project(this Vector2 vector, Vector2 onNormal)
  19. {
  20. float dotProduct = Vector2.Dot(vector, onNormal);
  21. float magnitudeSquared = onNormal.sqrMagnitude;
  22. if (magnitudeSquared < Mathf.Epsilon)
  23. return Vector2.zero;
  24. return (dotProduct / magnitudeSquared) * onNormal;
  25. }
  26. public static float LengthManhattan(this Vector2 v) => Math.Abs(v.x) + Math.Abs(v.y);
  27. public static double LengthManhattan(Vector2 v1, Vector2 v2) => (v1 - v2).LengthManhattan();
  28. // 可以用于判断点位V于直线AB哪一侧
  29. // return的值 等于0: 点在线上,大于0: 三角形ABV是逆时针,小于0: 三角形ABV是顺时针 (注:Line的构造函数会修改AB的顺序)
  30. public static float LineCrossWithPoint(this Line l, Vector v)
  31. {
  32. var ld = l.B - l.A;
  33. var vd = v - l.A;
  34. return ld.x * vd.y - ld.y * vd.x;
  35. }
  36. }
  37. }