CommonVectors.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7. namespace Bitsplash.Vector
  8. {
  9. class CommonVectors
  10. {
  11. public static List<Vector2> mTmpList = new List<Vector2>();
  12. public static List<Vector2> mTmpSmoothList = new List<Vector2>();
  13. public static Vector2 LineInsersection(Vector2 a1,Vector2 a2,Vector2 b1,Vector2 b2)
  14. {
  15. float A1 = a2.y - a1.y;
  16. float B1 = a1.x - a2.x;
  17. float C1 = A1 * a1.x + B1 * a1.y;
  18. float A2 = b2.y - b1.y;
  19. float B2 = b1.x - b2.x;
  20. float C2 = A2 * b1.x + B2 * b1.y;
  21. float delta = A1 * B2 - A2 * B1;
  22. float x = (B2 * C1 - B1 * C2) / delta;
  23. float y = (A1 * C2 - A2 * C1) / delta;
  24. return new Vector2(x, y);
  25. }
  26. static Vector2 Orthogonal(Vector2 v)
  27. {
  28. return new Vector2(v.y, -v.x);
  29. }
  30. static Vector2 FromPolar(float angle,float radius)
  31. {
  32. return new Vector2(Mathf.Cos(angle) * radius, Mathf.Sin(angle) * radius);
  33. }
  34. public static Vector2 InterpolateUV(Vector2 v,Vector2 min,Vector2 size)
  35. {
  36. return new Vector2((v.x - min.x) / size.x, (v.y - min.y) / size.y);
  37. }
  38. public static void NPolygon(int edgeCount,float radius,float alternateRadius,List<Vector2> res)
  39. {
  40. float startAngle = 90 - (180f / (float)edgeCount);
  41. for(int i=0; i<edgeCount; i++)
  42. {
  43. float angle = startAngle + ((float)i) / ((float)edgeCount) * 360;
  44. res.Add(FromPolar(angle * Mathf.Deg2Rad, radius));
  45. }
  46. }
  47. public static void SmoothCorners(List<Vector2> polygon,float offset,float segments, List<Vector2> res)
  48. {
  49. for(int i=0; i<polygon.Count; i++)
  50. {
  51. Vector2 p1 = polygon[i];
  52. Vector2 p2 = polygon[(i+1)%polygon.Count];
  53. Vector2 p3 = polygon[(i+2)% polygon.Count];
  54. Vector2 s1Dir = (p2 - p1).normalized;
  55. Vector2 s2Dir = (p3 - p2).normalized;
  56. Vector2 arcStart = p2 - s1Dir * offset;
  57. Vector2 arcEnd = p2 + s2Dir * offset;
  58. Vector2 arcCenter = LineInsersection(arcStart, arcStart + Orthogonal(s1Dir),arcEnd ,arcEnd+ Orthogonal(s2Dir));
  59. float startAngle = Mathf.Atan2(arcStart.y - arcCenter.y, arcStart.x - arcCenter.x);
  60. float endAngle = Mathf.Atan2(arcEnd.y - arcCenter.y, arcEnd.x - arcCenter.x);
  61. if (endAngle < startAngle)
  62. startAngle -= Mathf.PI * 2f;
  63. float radius = (arcStart - arcCenter).magnitude;
  64. for (int j=0; j<=segments; j++)
  65. {
  66. float factor = ((float)j) / ((float)segments);
  67. float angle = Mathf.Lerp(startAngle, endAngle, factor);
  68. res.Add(arcCenter + FromPolar(angle, radius));
  69. }
  70. }
  71. }
  72. }
  73. }