ZIMMath.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132
  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. }
  29. }