Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Splines;
- namespace sc.modeling.splines.runtime.auxiliary
- {
- public class CreateSplineFromPoints : MonoBehaviour
- {
- [Header("Input")]
- [Tooltip("Positional points in local-space")]
- public List<Vector3> points = new List<Vector3>()
- {
- new Vector3(-1f, 0f, -5f),
- new Vector3(1f, 0f, -2.5f),
- new Vector3(-1f, 0f, 0),
- new Vector3(1f, 0f, 2.5f),
- new Vector3(-1f, 0f, 5f),
- };
- [Space]
- [Header("Output")]
- public SplineContainer splineContainer;
- public bool smooth = true;
- private void Reset()
- {
- splineContainer = GetComponent<SplineContainer>();
- if (!splineContainer) splineContainer = this.gameObject.AddComponent<SplineContainer>();
- }
- private void OnValidate()
- {
- if (!splineContainer) return;
- int pointCount = points.Count;
- if (pointCount < 2) return;
- //First, delete all existing splines
- for (int s = 0; s < splineContainer.Splines.Count; s++)
- {
- splineContainer.RemoveSpline(splineContainer.Splines[s]);
- }
- Spline spline = new Spline(pointCount);
- for (int i = 0; i < pointCount; i++)
- {
- BezierKnot knot = new BezierKnot();
- knot.Position = points[i];
- knot.Rotation = Quaternion.identity;
- spline.Add(knot, smooth ? TangentMode.AutoSmooth : TangentMode.Linear);
- }
- //Automatically recalculate tangents
- spline.SetTangentMode(new SplineRange(0, spline.Count), smooth ? TangentMode.AutoSmooth : TangentMode.Linear);
- //Adding a spline automatically rebuilds the mesh
- splineContainer.AddSpline(spline);
- }
- private void OnDrawGizmosSelected()
- {
- if (!splineContainer) return;
- Gizmos.matrix = splineContainer.transform.localToWorldMatrix;
- foreach (Vector3 p in points)
- {
- Gizmos.DrawSphere(p, 0.25f);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement