使用Mesh绘制一个Cube

使用代码在unity中绘制形状

主要用到了两个组件:MeshFilter以及MeshRenderer

1、首先根据所要绘制的形状,定义一个坐标数组(Vector3[]),将形状的所有顶点存储到这个数组中

2、定义顶点绘制的顺序(unity绘制形状是按照三角形进行绘制的,按照顺时针排列,这里在实测的时候,顺时针绘制的形状为正面,当绘制三维物体的时候需要考虑绘制朝外的那个面来定义顶点的绘制顺序)

代码如下:

1、首先是定义顶点的方法,这里就需要考虑绘制面的朝向:

/// <summary>
    /// 绘制顶点
    /// </summary>
    /// <param name="_lenth"></param>
    /// <param name="_height"></param>
    /// <returns></returns>
    public Vector3[] GetVertex(float _lenth,float _height)
    {
        Vector3[] _rec = new Vector3[] {
            //正面
            new Vector3(0,0,0),
            new Vector3(0,_height,0),
            new Vector3(_lenth,0,0),
            new Vector3(0,_height,0),
            new Vector3(_lenth,_height,0),
            new Vector3(_lenth,0,0),
        
            //左侧
            new Vector3(0,0,0),
            new Vector3(0,0,_lenth),
            new Vector3(0,_height,0),
            new Vector3(0,_height,0),
            new Vector3(0,0,_lenth),
            new Vector3(0,_lenth,_height),
            //右侧
            new Vector3(_lenth,_lenth,_height),
            new Vector3(_lenth,0,_lenth),
            new Vector3(_lenth,_height,0),
            new Vector3(_lenth,_height,0),
            new Vector3(_lenth,0,_lenth),
            new Vector3(_lenth,0,0),
            //后侧
            new Vector3(_lenth,0,_lenth),
            new Vector3(_lenth,_height,_lenth),
            new Vector3(0,_height,_lenth),
            new Vector3(_lenth,0,_lenth),
            new Vector3(0,_height,_lenth),
            new Vector3(0,0,_lenth),

            //底部
            new Vector3(0,0,0),
            new Vector3(_lenth,0,0),
            new Vector3(_lenth,0,_lenth),
            new Vector3(_lenth,0,_lenth),
            new Vector3(0,0,_lenth),
            new Vector3(0,0,0),
    
            //上部
            new Vector3(0,_height,0),
            new Vector3(0, _height, _lenth),
            new Vector3(_lenth, _height, _lenth),
            new Vector3(_lenth, _height, _lenth),
            new Vector3(_lenth, _height, 0),
            new Vector3(0, _height, 0)
     
        };
        return _rec;
    }

 2、根据顶点创建绘制顺序数组

public int[] GetSort(Vector3[] _vec)
    {
        int[] rec = new int[_vec.Length];
        for (int i = 0; i < _vec.Length; i++) {
            rec[i] = i;
        }
        return rec;
    }

3、定义方法输出一个形状

   public Material _mat;
    private void DrawCube() {
        Mesh mesh = gameObject.AddComponent<MeshFilter>().mesh;
        MeshRenderer _render = gameObject.AddComponent<MeshRenderer>();
        _render.material = _mat;
        mesh.vertices =GetVertex(1, 1);
        mesh.triangles = GetSort(mesh.vertices);

        this.name = "cube";
        this.gameObject.AddComponent<BoxCollider>();

    }

猜你喜欢

转载自blog.csdn.net/sinat_28962939/article/details/103128790