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.

LineSmoother.cs 3.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. public class LineSmoother : MonoBehaviour
  5. {
  6. public static Vector3[] SmoothLine( Vector3[] inputPoints, float segmentSize )
  7. {
  8. //create curves
  9. AnimationCurve curveX = new AnimationCurve();
  10. AnimationCurve curveY = new AnimationCurve();
  11. AnimationCurve curveZ = new AnimationCurve();
  12. //create keyframe sets
  13. Keyframe[] keysX = new Keyframe[inputPoints.Length];
  14. Keyframe[] keysY = new Keyframe[inputPoints.Length];
  15. Keyframe[] keysZ = new Keyframe[inputPoints.Length];
  16. //set keyframes
  17. for( int i = 0; i < inputPoints.Length; i++ )
  18. {
  19. keysX[i] = new Keyframe( i, inputPoints[i].x );
  20. keysY[i] = new Keyframe( i, inputPoints[i].y );
  21. keysZ[i] = new Keyframe( i, inputPoints[i].z );
  22. }
  23. //apply keyframes to curves
  24. curveX.keys = keysX;
  25. curveY.keys = keysY;
  26. curveZ.keys = keysZ;
  27. //smooth curve tangents
  28. for( int i = 0; i < inputPoints.Length; i++ )
  29. {
  30. curveX.SmoothTangents( i, 0 );
  31. curveY.SmoothTangents( i, 0 );
  32. curveZ.SmoothTangents( i, 0 );
  33. }
  34. //list to write smoothed values to
  35. List<Vector3> lineSegments = new List<Vector3>();
  36. //find segments in each section
  37. for( int i = 0; i < inputPoints.Length; i++ )
  38. {
  39. //add first point
  40. lineSegments.Add( inputPoints[i] );
  41. //make sure within range of array
  42. if( i+1 < inputPoints.Length )
  43. {
  44. //find distance to next point
  45. float distanceToNext = Vector3.Distance(inputPoints[i], inputPoints[i+1]);
  46. //number of segments
  47. int segments = (int)(distanceToNext / segmentSize);
  48. //add segments
  49. for( int s = 1; s < segments; s++ )
  50. {
  51. //interpolated time on curve
  52. float time = ((float)s/(float)segments) + (float)i;
  53. //sample curves to find smoothed position
  54. Vector3 newSegment = new Vector3( curveX.Evaluate(time), curveY.Evaluate(time), curveZ.Evaluate(time) );
  55. //add to list
  56. lineSegments.Add( newSegment );
  57. }
  58. }
  59. }
  60. return lineSegments.ToArray();
  61. }
  62. }