Skip to content

Instantly share code, notes, and snippets.

@glitchersgames
Last active September 3, 2017 11:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glitchersgames/da0b20d069334c948696619955391f2e to your computer and use it in GitHub Desktop.
Save glitchersgames/da0b20d069334c948696619955391f2e to your computer and use it in GitHub Desktop.
Color a mesh based on progress along a 'spline' (read - series of unconnected transforms). Colors can be adjusted using curves. Do this in edit mode with a VertexColor shader/your custom one to see results live. WARNING: This affects the mesh directly so make sure to save a backup.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SplineVertexColors : MonoBehaviour {
#region Types
public enum Mode
{
ChannelCurves,
Gradient
}
#endregion
#region Serialized
public MeshFilter m_MeshFilter;
public Transform[] m_SplinePoints;
public Mode m_Mode = Mode.ChannelCurves;
[Header("Mode - Channel Curves")]
public AnimationCurve m_RedCurve = AnimationCurve.Linear(0f,0f,1f,1f);
public AnimationCurve m_GreenCurve = AnimationCurve.Linear(0f,0f,1f,1f);
public AnimationCurve m_BlueCurve = AnimationCurve.Linear(0f,0f,1f,1f);
public AnimationCurve m_AlphaCurve = AnimationCurve.Linear(0f,0f,1f,1f);
[Header("Mode - Gradient")]
public Gradient m_Gradient;
[Header("Debug")]
public bool m_DrawVertexSplineConnections = true;
#endregion
#region Lifecycle
private void Update()
{
UpdateMeshColors();
}
#endregion
#region Methods
private void UpdateMeshColors()
{
var mesh = m_MeshFilter.sharedMesh;
Vector3[] vertices = mesh.vertices;
Color[] colors = new Color[vertices.Length];
for( int i = 0; i < vertices.Length; i++ )
{
float vertProgress = GetVertexProgress( vertices[i] );
if( m_Mode == Mode.ChannelCurves )
{
colors[i] = new Color( m_RedCurve.Evaluate( vertProgress ), m_GreenCurve.Evaluate( vertProgress ), m_BlueCurve.Evaluate( vertProgress ), m_AlphaCurve.Evaluate( vertProgress ) );
}
else
{
colors[i] = m_Gradient.Evaluate( vertProgress );
}
}
mesh.colors = colors;
m_MeshFilter.sharedMesh = mesh;
}
private float GetVertexProgress( Vector3 vertexPosition )
{
float minDistanceSqr = Mathf.Infinity;
int minDistanceIndex = -1;
Vector3 vertexWorldPosition = transform.TransformPoint( vertexPosition );
for( int i = 0; i < m_SplinePoints.Length; i++ )
{
float distanceSqr = Vector3.SqrMagnitude( m_SplinePoints[i].position - vertexWorldPosition );
if( distanceSqr < minDistanceSqr )
{
minDistanceIndex = i;
minDistanceSqr = distanceSqr;
}
}
if( m_DrawVertexSplineConnections )
{
Debug.DrawLine( vertexWorldPosition, m_SplinePoints[minDistanceIndex].position, Color.blue );
}
return (float)minDistanceIndex/(float)(m_SplinePoints.Length-1);
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment