SuperellipsePoints.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /// <summary>
  2. /// Credit - ryanslikesocool
  3. /// Sourced from - https://github.com/ryanslikesocool/Unity-Card-UI
  4. /// </summary>
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using UnityEngine;
  8. namespace UnityEngine.UI.Extensions
  9. {
  10. ///The formula for a basic superellipse is
  11. ///Mathf.Pow(Mathf.Abs(x / a), n) + Mathf.Pow(Mathf.Abs(y / b), n) = 1
  12. [ExecuteInEditMode]
  13. public class SuperellipsePoints : MonoBehaviour
  14. {
  15. public float xLimits = 1f;
  16. public float yLimits = 1f;
  17. [Range(1f, 96f)]
  18. public float superness = 4f;
  19. private float lastXLim;
  20. private float lastYLim;
  21. private float lastSuper;
  22. [Space]
  23. [Range(1, 32)]
  24. public int levelOfDetail = 4;
  25. private int lastLoD;
  26. [Space]
  27. public Material material;
  28. private List<Vector2> pointList = new List<Vector2>();
  29. void Start()
  30. {
  31. RecalculateSuperellipse();
  32. GetComponent<MeshRenderer>().material = material;
  33. lastXLim = xLimits;
  34. lastYLim = yLimits;
  35. lastSuper = superness;
  36. lastLoD = levelOfDetail;
  37. }
  38. void Update()
  39. {
  40. if (lastXLim != xLimits || lastYLim != yLimits || lastSuper != superness || lastLoD != levelOfDetail)
  41. {
  42. RecalculateSuperellipse();
  43. }
  44. lastXLim = xLimits;
  45. lastYLim = yLimits;
  46. lastSuper = superness;
  47. lastLoD = levelOfDetail;
  48. }
  49. void RecalculateSuperellipse()
  50. {
  51. pointList.Clear();
  52. float realLoD = levelOfDetail * 4;
  53. for (float i = 0; i < xLimits; i += 1 / realLoD)
  54. {
  55. float y = Superellipse(xLimits, yLimits, i, superness);
  56. Vector2 tempVecTwo = new Vector2(i, y);
  57. pointList.Add(tempVecTwo);
  58. }
  59. pointList.Add(new Vector2(xLimits, 0));
  60. pointList.Add(Vector2.zero);
  61. GetComponent<MeshCreator>().CreateMesh(pointList);
  62. }
  63. float Superellipse(float a, float b, float x, float n)
  64. {
  65. float alpha = Mathf.Pow((x / a), n);
  66. float beta = 1 - alpha;
  67. float y = Mathf.Pow(beta, 1 / n) * b;
  68. return y;
  69. }
  70. }
  71. }