扇形攻击范围:使用代码生成mesh模拟扇形攻击范围:新建场景,新建一个Cube,此脚本挂在Cube上;
- public class DrawMeshSector : MonoBehaviour {
- //mesh代码生成的
- public GameObject go;
- MeshFilter mf;
- MeshRenderer mr;
- Shader shader;
- void Start()
- {
- }
- void Update()
- {
- if (Input.GetKeyDown(KeyCode.S))
- {
- ToDrawSector(transform,transform.localPosition,60,3);
- }
- }
- //生成网格
- public GameObject CreateMesh(List<Vector3> vertices)
- {
- int[] triangles;
- Mesh mesh = new Mesh();
- int triangleAmount = vertices.Count - 2;
- triangles = new int[3 * triangleAmount];
- //根据三角形的个数,来计算绘制三角形的顶点顺序
- //顺序必须为顺时针或者逆时针
- for (int i = 0; i < triangleAmount; i++)
- {
- triangles[3 * i] = 0;
- triangles[3 * i + 1] = i + 1;
- triangles[3 * i + 2] = i + 2;
- }
- if (go == null)
- {
- go = new GameObject("Sector");
- go.transform.SetParent(transform, false);
- go.transform.position = new Vector3(0, 0.1f, 0);
- mf = go.AddComponent<MeshFilter>();
- mr = go.AddComponent<MeshRenderer>();
- shader = Shader.Find("Unlit/Color");
- }
- //分配一个新的顶点位置数组
- mesh.vertices = vertices.ToArray();
- //包含网格中所有三角形的数组
- mesh.triangles = triangles;
- mf.mesh = mesh;
- mr.material.shader = shader;
- mr.material.color = Color.red;
- return go;
- }
- /// <summary>
- /// 画弧度角扇形
- /// </summary>
- /// <param name="t">参考方向</param>
- /// <param name="center">位置</param>
- /// <param name="angle">角度</param>
- /// <param name="radius">半径</param>
- private void ToDrawSector(Transform t,Vector3 center,float angle,float radius)
- {
- int pointAmmount = 100;
- float eachAngle = angle / pointAmmount;
- Vector3 forward = t.forward;
- List<Vector3> vertices = new List<Vector3>();
- vertices.Add(center);
- for (int i = 0; i < pointAmmount; i++)
- {
- Vector3 pos = Quaternion.Euler(0, -angle / 2 + eachAngle * (i - 1), 0) * forward * radius;
- vertices.Add(pos);
- }
- CreateMesh(vertices);
- }
- }