切換
舊版
前往
大廳
主題

Unity 程式功能 (3) - 繪製扇形(Mesh Ver)

三角形 | 2020-11-17 17:40:07 | 巴幣 0 | 人氣 100

public class DrawSector : MonoBehaviour {

    public float Radius = 6; // 外半徑
    public float innerRadius = 3; // 內半徑
    public float angleDegree = 360; // 扇形或扇面角度
    public int Segments = 60; // 分割數
    public MeshFilter meshFilter;

    private void Start() {
        meshFilter = GetComponent<MeshFilter>();
    }

    private void Update() {
        meshFilter.mesh = CreateMesh(Radius, innerRadius, angleDegree, Segments);
    }

    Mesh CreateMesh(float radius, float innerRadius, float angledegree, int segments) {

        // vertices(頂點):
        int vertices_count = segments * 2 + 2; // 因為vertices(頂點)的個數與triangles(索引三角形個數)必須匹配
        Vector3[] vertices = new Vector3[vertices_count];
        float angleRad = Mathf.Deg2Rad * angledegree;
        float angleCur = angleRad;
        float angledelta = angleRad / segments;
        for (int i = 0; i < vertices_count; i += 2) {
            float cosA = Mathf.Cos(angleCur);
            float sinA = Mathf.Sin(angleCur);
            vertices[i] = new Vector3(radius * cosA, 0, radius * sinA);
            vertices[i + 1] = new Vector3(innerRadius * cosA, 0, innerRadius * sinA);
            angleCur -= angledelta;
        }

        // triangles:
        int triangle_count = segments * 6;
        int[] triangles = new int[triangle_count];
        for (int i = 0, vi = 0; i < triangle_count; i += 6, vi += 2) {
            triangles[i] = vi;
            triangles[i + 1] = vi + 3;
            triangles[i + 2] = vi + 1;
            triangles[i + 3] = vi + 2;
            triangles[i + 4] = vi + 3;
            triangles[i + 5] = vi;
        }

        // uv:
        Vector2[] uvs = new Vector2[vertices_count];
        for (int i = 0; i < vertices_count; i++) {
            uvs[i] = new Vector2(vertices[i].x / radius / 2 + 0.5f, vertices[i].y / radius / 2 + 0.5f);
        }

        // 負載屬性於 mesh
        Mesh mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uvs;
        return mesh;
    }

}

參考資料: https://gameinstitute.qq.com/community/detail/128550

創作回應

更多創作