Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using Unity.Mathematics;
- 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<float3> points = new List<float3>()
- {
- new float3(-1f, 0f, -5f),
- new float3(1f, 0f, -2.5f),
- new float3(-1f, 0f, 0),
- new float3(1f, 0f, 2.5f),
- new float3(-1f, 0f, 5f),
- };
- [Space]
- [Header("Output")]
- public SplineContainer splineContainer;
- public bool closed = false;
- [Tooltip("The error threshold to use. Represents the largest distance between any of the provided points and the curve.")]
- public float errorThreshold = 0.85f;
- private void Reset()
- {
- splineContainer = GetComponent<SplineContainer>();
- if (!splineContainer) splineContainer = this.gameObject.AddComponent<SplineContainer>();
- }
- private void OnValidate()
- {
- if (!splineContainer)
- {
- throw new Exception("Failed to create a spline from a position list. No SplineContainer is assigned to the component");
- }
- int pointCount = points.Count;
- if (pointCount < 2)
- {
- throw new Exception("Failed to create a spline from a position list. At least 2 points need to be provided");
- }
- //First, delete all existing splines
- for (int s = 0; s < splineContainer.Splines.Count; s++)
- {
- splineContainer.RemoveSpline(splineContainer.Splines[s]);
- }
- var pointsCopy = new List<float3>(points);
- //Convert points from world-space to local-space
- for (int i = 0; i < points.Count; i++)
- {
- pointsCopy[i] = splineContainer.transform.InverseTransformPoint(points[i]);
- }
- SplineUtility.FitSplineToPoints(pointsCopy, errorThreshold, closed, out var spline);
- //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