Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using UnityEngine;
- using UnityEngine.Splines;
- namespace sc.modeling.splines.runtime.auxiliary
- {
- //Samples the source spline at regular intervals and creates a new spline from the data
- //Negatives the unwanted side effects of scaling a SplineContainer
- [ExecuteAlways]
- public class ReprojectSpline : MonoBehaviour
- {
- public SplineContainer source;
- public SplineContainer destination;
- public float knotDistance = 2f;
- private void Reset()
- {
- destination = GetComponent<SplineContainer>();
- }
- private void OnEnable()
- {
- Spline.Changed += OnSplineChanged;
- Resample();
- }
- private void OnDisable()
- {
- Spline.Changed -= OnSplineChanged;
- }
- private void OnSplineChanged(Spline spline, int index, SplineModification modificationType)
- {
- if (!source) return;
- if (spline.GetHashCode() != source.GetHashCode()) return;
- //Spline belongs to the assigned container?
- var splineIndex = Array.IndexOf(source.Splines.ToArray(), spline);
- if (splineIndex < 0)
- return;
- Resample();
- }
- public void Resample()
- {
- if (!source || !destination) return;
- for (int s = 0; s < destination.Splines.Count; s++)
- {
- destination.RemoveSplineAt(s);
- }
- for (int i = 0; i < source.Splines.Count; i++)
- {
- Spline spline = new Spline();
- float length = source.Splines[i].CalculateLength(source.transform.localToWorldMatrix);
- int sampleCount = Mathf.CeilToInt(length / knotDistance);
- for (int j = 0; j <= sampleCount; j++)
- {
- float t = (float) j / sampleCount;
- t = Mathf.Clamp(t, 0.001f, 0.999f);
- source.Splines[i].Evaluate(t, out var position, out var tangent, out var up);
- position = source.transform.TransformPoint(position);
- position = destination.transform.InverseTransformPoint(position);
- BezierKnot knot = new BezierKnot();
- knot.Position = position;
- spline.Add(knot, TangentMode.Continuous);
- }
- //Automatically recalculate tangents
- spline.SetTangentMode(new SplineRange(0, spline.Count), TangentMode.AutoSmooth);
- spline.Closed = source.Splines[i].Closed;
- destination.AddSpline(spline);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement