You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CurvedLineRenderer.cs 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. [RequireComponent( typeof(LineRenderer) )]
  5. public class CurvedLineRenderer : MonoBehaviour
  6. {
  7. //PUBLIC
  8. public float lineSegmentSize = 0.15f;
  9. public float lineWidth = 0.1f;
  10. [Header("Gizmos")]
  11. public bool showGizmos = true;
  12. public float gizmoSize = 0.1f;
  13. public Color gizmoColor = new Color(1,0,0,0.5f);
  14. //PRIVATE
  15. private CurvedLinePoint[] linePoints = new CurvedLinePoint[0];
  16. private Vector3[] linePositions = new Vector3[0];
  17. private Vector3[] linePositionsOld = new Vector3[0];
  18. // Update is called once per frame
  19. public void Update ()
  20. {
  21. GetPoints();
  22. SetPointsToLine();
  23. }
  24. void GetPoints()
  25. {
  26. //find curved points in children
  27. linePoints = this.GetComponentsInChildren<CurvedLinePoint>();
  28. //add positions
  29. linePositions = new Vector3[linePoints.Length];
  30. for( int i = 0; i < linePoints.Length; i++ )
  31. {
  32. linePositions[i] = linePoints[i].transform.position;
  33. }
  34. }
  35. void SetPointsToLine()
  36. {
  37. //create old positions if they dont match
  38. if( linePositionsOld.Length != linePositions.Length )
  39. {
  40. linePositionsOld = new Vector3[linePositions.Length];
  41. }
  42. //check if line points have moved
  43. bool moved = false;
  44. for( int i = 0; i < linePositions.Length; i++ )
  45. {
  46. //compare
  47. if( linePositions[i] != linePositionsOld[i] )
  48. {
  49. moved = true;
  50. }
  51. }
  52. //update if moved
  53. if( moved == true )
  54. {
  55. LineRenderer line = this.GetComponent<LineRenderer>();
  56. //get smoothed values
  57. Vector3[] smoothedPoints = LineSmoother.SmoothLine( linePositions, lineSegmentSize );
  58. //set line settings
  59. line.SetVertexCount( smoothedPoints.Length );
  60. line.SetPositions( smoothedPoints );
  61. line.SetWidth( lineWidth, lineWidth );
  62. }
  63. }
  64. void OnDrawGizmosSelected()
  65. {
  66. Update();
  67. }
  68. void OnDrawGizmos()
  69. {
  70. if( linePoints.Length == 0 )
  71. {
  72. GetPoints();
  73. }
  74. //settings for gizmos
  75. foreach( CurvedLinePoint linePoint in linePoints )
  76. {
  77. linePoint.showGizmo = showGizmos;
  78. linePoint.gizmoSize = gizmoSize;
  79. linePoint.gizmoColor = gizmoColor;
  80. }
  81. }
  82. }