Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using Unity.Mathematics;
- using UnityEngine;
- using UnityEngine.Splines;
- namespace sc.modeling.splines.runtime.auxiliary
- {
- //This component may be used to fix a Transform to either the start or end of a spline
- [ExecuteAlways]
- public class AttachTransformToSpline : MonoBehaviour
- {
- public SplineContainer splineContainer;
- public enum ConnectionPoint
- {
- Start,
- End,
- Custom
- }
- [Space]
- public ConnectionPoint point;
- public PathIndexUnit customPositionType = PathIndexUnit.Distance;
- public float customPosition;
- [Space]
- [Header("Position")]
- public Vector3 offset;
- [Space]
- [Header("Rotation")]
- public bool alignRotation = true;
- public Vector3 addedRotation;
- private void Reset()
- {
- splineContainer = gameObject.GetComponentInParent<SplineContainer>();
- Apply();
- }
- private void OnEnable()
- {
- Spline.Changed += OnSplineChanged;
- }
- private void OnDisable()
- {
- Spline.Changed -= OnSplineChanged;
- }
- private void OnSplineChanged(Spline spline, int index, SplineModification modificationType)
- {
- if (!splineContainer) return;
- //Spline belongs to the assigned container?
- var splineIndex = Array.IndexOf(splineContainer.Splines.ToArray(), spline);
- if (splineIndex < 0)
- return;
- Apply();
- }
- private void OnValidate()
- {
- Apply();
- }
- private void Apply()
- {
- if (!splineContainer) return;
- float t = 0f;
- switch (point)
- {
- case ConnectionPoint.Start: t = 0f;
- break;
- case ConnectionPoint.End: t = 1f;
- break;
- case ConnectionPoint.Custom: t = customPosition;
- break;
- }
- if (point == ConnectionPoint.Custom && customPositionType == PathIndexUnit.Distance)
- {
- t = splineContainer.Spline.ConvertIndexUnit(customPosition, PathIndexUnit.Distance, PathIndexUnit.Normalized);
- }
- //Ensure a tangent can always be derived at very the start and end
- t = Mathf.Clamp(t, 0.0001f, 0.9999f);
- splineContainer.Spline.Evaluate(t, out float3 splinePoint, out float3 tangent, out float3 up);
- float3 position = splinePoint;
- float3 forward = math.normalize(tangent);
- float3 right = -math.cross(forward, up);
- //Offset
- position += right * offset.x;
- position += up * offset.y;
- position += forward * offset.z;
- //Position of point on spline in world-space
- position = splineContainer.transform.TransformPoint(position);
- this.transform.position = position;
- if (alignRotation)
- {
- Quaternion rotation = Quaternion.LookRotation(forward) * Quaternion.Euler(addedRotation);
- this.transform.rotation = rotation;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement