-
-
Save FreyaHolmer/9ff1a9df185afbd74d5244f13b5191c0 to your computer and use it in GitHub Desktop.
Reveals a Polyline component in Shapes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using Freya; | |
using Shapes; | |
using UnityEngine; | |
[RequireComponent( typeof(Polyline) )] | |
public class PolylineRevealer : MonoBehaviour { | |
// Animate this to reveal the line. 0 = invisible, 1 = fully visible | |
[Range( 0, 1 )] public float t; | |
List<PolylinePoint> originalPoints; | |
List<float> distances; | |
Polyline polyline; | |
void Awake() { | |
polyline = GetComponent<Polyline>(); | |
// Cache the original points so that we don't lose them when editing the polyline | |
originalPoints = new List<PolylinePoint>(); | |
originalPoints.AddRange( polyline.points ); | |
// Cache the distances between the points so that we can reveal with a uniform speed | |
distances = new List<float> { 0 }; | |
for( int i = 1; i < originalPoints.Count; i++ ) { | |
Vector3 prev = originalPoints[i - 1].point; | |
Vector3 next = originalPoints[i].point; | |
distances.Add( distances[i - 1] + Vector3.Distance( prev, next ) ); | |
} | |
} | |
// Updates the polyline based on the t-value. | |
void UpdatePolyline() { | |
polyline.points.Clear(); | |
if( t > 0 ) { | |
float dist = t * distances[^1]; | |
for( int i = 0; i < originalPoints.Count - 1; i++ ) { | |
float dPrev = distances[i]; | |
float dNext = distances[i + 1]; | |
if( dist > dPrev ) | |
polyline.points.Add( originalPoints[i] ); | |
if( dist <= dNext ) { | |
float tIntp = Mathfs.InverseLerp( dPrev, dNext, dist ); | |
PolylinePoint pt = PolylinePoint.Lerp( originalPoints[i], originalPoints[i + 1], tIntp ); | |
polyline.points.Add( pt ); | |
break; | |
} | |
} | |
} | |
polyline.meshOutOfDate = true; | |
} | |
// live update when changing t in the inspector, in play mode | |
void OnValidate() { | |
if( Application.isPlaying ) | |
UpdatePolyline(); | |
} | |
// ensures it updates when animating | |
void OnDidApplyAnimationProperties() => UpdatePolyline(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @FreyaHolmer I've been having an issue where the OnValidate() function is called before the originalPoints list gets populated for some reason.
Therefore when I hit Play, the polyline disappears, the polyline points in the inspector are cleared and the reveal doesn't work. I fixed the issue by adding extra check on line 55, but you might know a better way:
if (Application.isPlaying && originalPoints.Count > 0)
There's also a small syntax error on line 43:
Mathf.InverseLerp
instead ofMathfs.InverseLerp
The code performs well after I make the above changes.
Thanks for sharing!