Unity 自定义 飘带脚本
我们知道Unity自己默认带了TrailRender来实现飘带的效果,但是遇到一个问题是当Time暂停的时候移动物体依然会在继续创建飘带,会产生源源不断的飘带,我感觉是他销毁的时间计算是用的Time.deltaTime来累加的,而不是使用Time.unscaledDeltaTime。
那么正好这里需要一个在Time.timeScale为0的情况下依然能够正常表现的飘带。
参考Unity的TrailRenderer的表现,他是一个依据物体位置去跟随创建新的Mesh的一个过程,那么按照这个思想,我们记录父体的路径和位置,然后根据位置延展开一个Mesh,在延展的时候去设置宽度和颜色,就可以实现跟随节点位置创建对应的飘带了。
PS: 我们使用mesh的顶点颜色来显示,那么如果使用的shader没有顶点着色的话,就显示不出来我们额外添加的颜色。同时我们针对颜色和宽度 都使用插值来计算,这样做到颜色和线条的平滑。
自定义Point节点
处于我们自己管理的需要,我们自定义了点的结构。以及对应的运算。
private class Point
{
public float fadeAlpha = 0;
public Vector3 position = Vector3.zero;//位置
public float timeCreated = 0;//生命
public Point(Vector3 pos) {
position = pos;
timeCreated = Time.realtimeSinceStartup;
}
public float timeAlive {
get { return Time.realtimeSinceStartup - timeCreated; }
}
public static Point Lerp(Point p1, Point p2, float k) {
return new Point(Vector3.Lerp(p1.position, p2.position, k));
}
public static Point operator -(Point p1, Point p2) {
return new Point(p1.position - p2.position);
}
public static Point operator *(float k, Point p1) {
return new Point(k * p1.position);
}
public static Point operator +(Point p1, Point p2) {
return new Point(p1.position + p2.position);
}
}
创建
一开始的时候初始化一个点的列表,作为缓存池,然后有一个计数器,来记录有多少点是需要合并到Mesh里面的。
创建一个新的Object作为飘带的载体,添加需要的Mesh脚本。
trail = new GameObject("Trail");
MeshFilter meshFilter = trail.AddComponent<MeshFilter>();
mesh = meshFilter.mesh;
trail.AddComponent<MeshRenderer>();
更新
实时更新Point的列表,先把时间超出的点去除,因为我们是按序一个个累加的,所以只要将列表最先一个时间为超出的更新到列表第一位就可以了。
//当地一个点的时间不到销毁,则直接返回原本数组即可
if (saved[0] == null)
{
return;
}
if (saved[0].timeAlive < lifeTime)
{
return;
}
int forwardIndex = -1;
for (int i = 1; i < savedCnt; i++)
{
Point pt = saved[i];
if (forwardIndex < 0)
{
if (pt.timeAlive < lifeTime)
{
forwardIndex = i;
}
if (forwardIndex < 0 && i == savedCnt - 1)
{
forwardIndex = i;
}
}
if (forwardIndex > 0)
{
saved[i - forwardIndex] = saved[i];
}
}
if (forwardIndex > 0)
{
savedCnt -= forwardIndex;
rebuildMesh = true;
}
然后获取当前的位置,移动的距离超过了最小距离,表示需要重建Mesh(肯定不是每帧都重建,只有需要改变Mesh点的时候才重建),那么我们就以当前的方向为中心轴,两边扩散出两个点,和前一次扩散的点来组合出两个三角形,合并到大网格中。就实现了Mesh的更新,同时我们将Mesh的顶点色填充进去,来实现中心到边缘颜色扩散递减的效果。
// Rebuild the mesh
Color[] meshColors;
Vector3[] vertices = new Vector3[savedCnt * 2];
Vector2[] uvs = new Vector2[savedCnt * 2];
int[] triangles = new int[(savedCnt - 1) * 6];
meshColors = new Color[savedCnt * 2];
float pointRatio = 1f / (savedCnt - 1);
float uvMultiplier = 1 / (saved[savedCnt - 1].timeAlive - saved[0].timeAlive);
for (int i = 0; i < savedCnt; i++)
{
Point point = saved[i];
float ratio = i * pointRatio;
// Color
Color color = GetColor(ratio);
meshColors[i * 2] = color;
meshColors[i * 2 + 1] = color;
Vector3 dir = GetDir(i);
// Width
float width = GetWidth(ratio);
vertices[i * 2] = point.position + dir * width * 0.5f;
vertices[i * 2 + 1] = point.position - dir * width * 0.5f;
// UVs
//float uvRatio = (point.timeAlive - saved[0].timeAlive) * uvMultiplier;
uvs[i * 2] = new Vector2(ratio, 0);
uvs[(i * 2) + 1] = new Vector2(ratio, 1);
if (i > 0)
{
// Triangles
int triIndex = (i - 1) * 6;
int vertIndex = i * 2;
triangles[triIndex + 0] = vertIndex - 2;
triangles[triIndex + 1] = vertIndex + 0;
triangles[triIndex + 2] = vertIndex + 1;
triangles[triIndex + 3] = vertIndex - 2;
triangles[triIndex + 4] = vertIndex + 1;
triangles[triIndex + 5] = vertIndex - 1;
}
}
trail.transform.position = Vector3.zero;
trail.transform.rotation = Quaternion.identity;
mesh.Clear();
mesh.vertices = vertices;
mesh.colors = meshColors;
mesh.uv = uvs;
mesh.triangles = triangles;
mesh.Optimize();
PS
1.取颜色的插值
思想很简单,比较麻烦的是考虑到边界的一些情况。
public Color GetColor(float ratio)
{
// Color
Color color;
if (colors.Length == 0)
{
color = Color.white;
}
else if (colors.Length == 1)
{
color = colors[0];
}
else if (colors.Length == 2)
{
color = Color.Lerp(colors[1], colors[0], ratio);
}
else
{
float colorRatio = ratio * (colors.Length - 1);
int min = (int)Mathf.Floor(colorRatio);
if (min == colors.Length - 1)
{
color = colors[min];
}
else
{
float lerp = colorRatio - min;
color = Color.Lerp(colors[min], colors[min + 1], lerp);
}
}
return color;
}
2.取宽度的插值,为了实现刚出生的时候,宽度大,快死亡的时候 ,宽度小。
private float GetWidth(float ratio)
{
// Width
return Mathf.Lerp(tailWidth, headWidth, ratio);
}
全部的脚本代码:
using UnityEngine;
public class MineTrailRenderer : MonoBehaviour
{
// Colors
public Color[] colors;
/// <summary>
/// 头的宽度
/// </summary>
public float headWidth = 1f;
// Lifetime of each segment
public float lifeTime = 1;
// Material - Particle Shader with "Tint Color" property
public Material material;
public float minVerticeDistance = 1f;
// Print Output
public bool printSavedPoints = false;
/// <summary>
/// 尾的宽度
/// </summary>
public float tailWidth = 1f;
private Mesh mesh = null;
private bool rebuildMesh = false;
// Points
private Point[] saved;
private int savedCnt = 0;
private Point[] savedUp;
// Objects
private GameObject trail = null;
public Color GetColor(float ratio)
{
// Color
Color color;
if (colors.Length == 0)
{
color = Color.white;
}
else if (colors.Length == 1)
{
color = colors[0];
}
else if (colors.Length == 2)
{
color = Color.Lerp(colors[1], colors[0], ratio);
}
else
{
float colorRatio = ratio * (colors.Length - 1);
int min = (int)Mathf.Floor(colorRatio);
if (min == colors.Length - 1)
{
color = colors[min];
}
else
{
float lerp = colorRatio - min;
color = Color.Lerp(colors[min], colors[min + 1], lerp);
}
}
return color;
}
public Vector3 GetDir(int index)
{
Vector3 dir;
if (index == 0)
{
dir = (saved[index + 1].position - saved[index].position).normalized;
}
else
{
dir = (saved[index].position - saved[index - 1].position).normalized;
}
return Vector3.Cross(dir, transform.up).normalized;
}
private void EliminatePoints()
{
//当地一个点的时间不到销毁,则直接返回原本数组即可
if (saved[0] == null)
{
return;
}
if (saved[0].timeAlive < lifeTime)
{
return;
}
int forwardIndex = -1;
for (int i = 1; i < savedCnt; i++)
{
Point pt = saved[i];
if (forwardIndex < 0)
{
if (pt.timeAlive < lifeTime)
{
forwardIndex = i;
}
if (forwardIndex < 0 && i == savedCnt - 1)
{
forwardIndex = i;
}
}
if (forwardIndex > 0)
{
saved[i - forwardIndex] = saved[i];
}
}
if (forwardIndex > 0)
{
savedCnt -= forwardIndex;
rebuildMesh = true;
}
}
private float GetWidth(float ratio)
{
// Width
return Mathf.Lerp(tailWidth, headWidth, ratio);
}
private void printPoints()
{
if (savedCnt == 0)
return;
string s = "Saved Points at time " + Time.time + ":\n";
for (int i = 0; i < savedCnt; i++)
s += "Index: " + i + "\tPos: " + saved[i] + "\n";
print(s);
}
private void Start()
{
// Data Inititialization
saved = new Point[100];
savedUp = new Point[saved.Length];
// Create the mesh object
trail = new GameObject("Trail");
trail.transform.position = Vector3.zero;
trail.transform.rotation = Quaternion.identity;
trail.transform.localScale = Vector3.one;
MeshFilter meshFilter = trail.AddComponent<MeshFilter>();
mesh = meshFilter.mesh;
trail.AddComponent<MeshRenderer>();
trail.GetComponent<Renderer>().material = material;
}
private void Update()
{
try
{
// Remove expired points
EliminatePoints();
Vector3 position = transform.position;
Point p = new Point(position);
Point normal = new Point(transform.TransformPoint(0, 0, 1));
if (savedCnt <= 0 || (position - saved[savedCnt - 1].position).sqrMagnitude >= minVerticeDistance)
{
//Add New Points
saved[savedCnt] = new Point(position);
savedCnt++;
rebuildMesh = true;
}
if (printSavedPoints)
{
printPoints();
}
if (savedCnt <= 1)
{
trail.gameObject.SetActive(false);
return;
}
if (rebuildMesh)
{
if (!trail.gameObject.activeInHierarchy)
{
trail.gameObject.SetActive(true);
}
// Common data
Color[] meshColors;
// Rebuild the mesh
Vector3[] vertices = new Vector3[savedCnt * 2];
Vector2[] uvs = new Vector2[savedCnt * 2];
int[] triangles = new int[(savedCnt - 1) * 6];
meshColors = new Color[savedCnt * 2];
float pointRatio = 1f / (savedCnt - 1);
float uvMultiplier = 1 / (saved[savedCnt - 1].timeAlive - saved[0].timeAlive);
for (int i = 0; i < savedCnt; i++)
{
Point point = saved[i];
float ratio = i * pointRatio;
// Color
Color color = GetColor(ratio);
meshColors[i * 2] = color;
meshColors[i * 2 + 1] = color;
Vector3 dir = GetDir(i);
// Width
float width = GetWidth(ratio);
vertices[i * 2] = point.position + dir * width * 0.5f;
vertices[i * 2 + 1] = point.position - dir * width * 0.5f;
// UVs
//float uvRatio = (point.timeAlive - saved[0].timeAlive) * uvMultiplier;
uvs[i * 2] = new Vector2(ratio, 0);
uvs[(i * 2) + 1] = new Vector2(ratio, 1);
if (i > 0)
{
// Triangles
int triIndex = (i - 1) * 6;
int vertIndex = i * 2;
triangles[triIndex + 0] = vertIndex - 2;
triangles[triIndex + 1] = vertIndex + 0;
triangles[triIndex + 2] = vertIndex + 1;
triangles[triIndex + 3] = vertIndex - 2;
triangles[triIndex + 4] = vertIndex + 1;
triangles[triIndex + 5] = vertIndex - 1;
}
}
trail.transform.position = Vector3.zero;
trail.transform.rotation = Quaternion.identity;
mesh.Clear();
mesh.vertices = vertices;
mesh.colors = meshColors;
mesh.uv = uvs;
mesh.triangles = triangles;
mesh.Optimize();
rebuildMesh = false;
}
}
catch (System.Exception e)
{
print(e);
}
}
private class Point
{
public float fadeAlpha = 0;
public Vector3 position = Vector3.zero;
public float timeCreated = 0;
public Point(Vector3 pos)
{
position = pos;
timeCreated = Time.realtimeSinceStartup;
}
public float timeAlive
{
get { return Time.realtimeSinceStartup - timeCreated; }
}
public static Point Lerp(Point p1, Point p2, float k)
{
return new Point(Vector3.Lerp(p1.position, p2.position, k));
}
public static Point operator -(Point p1, Point p2)
{
return new Point(p1.position - p2.position);
}
public static Point operator *(float k, Point p1)
{
return new Point(k * p1.position);
}
public static Point operator +(Point p1, Point p2)
{
return new Point(p1.position + p2.position);
}
public void update(Vector3 pos)
{
position = pos;
timeCreated = Time.realtimeSinceStartup;
}
}
}
参考资料:
维基百科 里面挺多好玩的东西呢。