Unity mesh 画线 line
image.pngusing System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;public class MyLine : MaskableGraphic{ public Color[] LineColor = new Color[] { new Color(0, 1, 0, 0.5f), Color.red, Color.blue }; public Vector3 p1; public Vector3 p2; public Vector3[] points; public float LineWidth = 1; protected override void OnPopulateMesh(VertexHelper vh) { vh.Clear(); if (points.Length < 2) { return; } //获取绕Z轴旋转90度的矩阵 这样就可以得到垂直于这条线段的点 就能根据宽度绘制mesh点 var mr = GetMatrixRotateZ(90); var ml = GetMatrixRotateZ(-90); for (int i = 0; i < points.Length - 1; i++) { Vector3 p0r = RotatePoint(points, points, mr); Vector3 p0l = RotatePoint(points, points, ml); Vector3 p1r = RotatePoint(points, points, mr); Vector3 p1l = RotatePoint(points, points, ml); //添加点 vh.AddVert(p0r, LineColor, Vector2.zero); vh.AddVert(p0l, LineColor, Vector2.zero); vh.AddVert(p1r, LineColor, Vector2.zero); vh.AddVert(p1l, LineColor, Vector2.zero); int baseIndex = i * 4; //添加面 vh.AddTriangle(baseIndex + 0, baseIndex + 2, baseIndex + 1); vh.AddTriangle(baseIndex + 0, baseIndex + 3, baseIndex + 2); } //下面注释是只有两个点 不使用循环写法 //Vector3 pp1 = mr * (p1 - p2).normalized; //Vector3 pp2 = ml * (p1 - p2).normalized; //Vector3 pp3 = mr * (p2 - p1).normalized; //Vector3 pp4 = ml * (p2 - p1).normalized; //pp1 *= LineWidth; //pp2 *= LineWidth; //pp3 *= LineWidth; //pp4 *= LineWidth; //pp1 += p1; //pp2 += p1; //pp3 += p2; //pp4 += p2; //vh.AddVert(pp1, c, Vector2.zero); //vh.AddVert(pp2, c, Vector2.zero); //vh.AddVert(pp3, c, Vector2.zero); //vh.AddVert(pp4, c, Vector2.zero); //vh.AddTriangle(0, 2, 1); //vh.AddTriangle(0, 3, 2); } public Vector3 RotatePoint(Vector3 p1, Vector3 p2, Matrix4x4 m) { //p1 - p2 得到两点连线指向p1的向量 标准化后长度为1 左乘矩阵后得到垂直向量 Vector3 pp1 = m * (p1 - p2).normalized; //由于原向量标准化了 所以旋转后的向量长度还是1 所以直接乘上宽度 pp1 *= LineWidth; //向量相加 得到点的坐标(Vector3 既可以是坐标 也可以是方向 注意区分算出来的结果是坐标还是方向) pp1 += p1; return pp1; } //构造一个 旋转矩阵 public Matrix4x4 GetMatrixRotateZ(float angle = 90) { angle = angle * Mathf.Deg2Rad; var rotateZMatrix = Matrix4x4.identity; rotateZMatrix.m00 = Mathf.Cos(angle); rotateZMatrix.m01 = Mathf.Sin(angle); rotateZMatrix.m10 = -Mathf.Sin(angle); rotateZMatrix.m11 = Mathf.Cos(angle); return rotateZMatrix; }}
页:
[1]