Skip to content

Instantly share code, notes, and snippets.

@MattRix
Created March 7, 2020 21:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattRix/07c4c966c5f5a7012061370b32fbecaf to your computer and use it in GitHub Desktop.
Save MattRix/07c4c966c5f5a7012061370b32fbecaf to your computer and use it in GitHub Desktop.
A simple single bezier line graphic with a repeating texture pattern
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
[RequireComponent(typeof(CanvasRenderer))]
public class BezierLineRenderer : Graphic
{
public Texture texture;
public Color endColor = new Color(1,1,1,1);
public override Texture mainTexture {get {return texture;}}
public Vector2 startPos = new Vector2(0,0);
public Vector2 startHandlePos = new Vector2(0,0);
public Vector2 endHandlePos = new Vector2(0,0);
public Vector2 endPos = new Vector2(0,0);
public float thickness = 7f;
public float distPerPoint = 6f;
public float distancePerPattern = 10f;
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
var approxLength = (startHandlePos-startPos).magnitude + (endHandlePos-startHandlePos).magnitude + (endPos-endHandlePos).magnitude;
int numPoints = Mathf.Max(2,Mathf.CeilToInt(approxLength/distPerPoint));
float percentPerPoint = 1f / (numPoints-1);
var points = new Vector2[numPoints+2];
var leftPoints = new Vector2[numPoints];
var rightPoints = new Vector2[numPoints];
for(int p = 0; p<numPoints; p++)
{
points[p+1] = RXMath.GetBezier(percentPerPoint*(float)p,startPos,startHandlePos,endHandlePos,endPos);
}
//add an extra point on each end of the path, for easier math later (we will NOT actually render these points though!)
points[0] = points[1] - (points[2] - points[1]); //point before start
points[points.Length-1] = points[points.Length-2] - (points[points.Length-3] - points[points.Length-2]); //point after end
var startColor32 = (Color32)color;
var endColor32 = (Color32)endColor;
float numTextureRepeats = approxLength/distancePerPattern;
for(int p = 0; p<numPoints; p++)
{
float percent = (float)p/(float)(numPoints-1);
var useColor32 = Color32.Lerp(startColor32,endColor32,percent);
Vector2 dirA = (points[p+2] - points[p+1]);
Vector2 dirB = (points[p+1] - points[p]);
Vector2 avgDir = (dirA + dirB).normalized;
Vector2 offset = new Vector2(-avgDir.y,avgDir.x) * thickness * 0.5f;
leftPoints[p] = points[p+1] + offset;
rightPoints[p] = points[p+1] - offset;
vh.AddVert(leftPoints[p],useColor32,new Vector2(percent*numTextureRepeats,1f));
vh.AddVert(rightPoints[p],useColor32,new Vector2(percent*numTextureRepeats,0));
}
for(int p = 0; p<numPoints-1; p++)
{
int i = p*2;
vh.AddTriangle(i,i+2,i+1);
vh.AddTriangle(i+2,i+3,i+1);
}
}
public void MarkNeedsChange()
{
this.SetVerticesDirty();
this.SetMaterialDirty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment