Unity之使用Mesh创建一个Cube(二)

https://docs.unity3d.com/Manual/Example-CreatingaBillboardPlane.html
如何用Mesh创建立方体,

  我们都知道Cube有六个面(我们把它分为Front,Back,Left,Right,Up,Down),八个顶点,我们画草图进行分析(为了分析方便我用的Unity引擎自带立方体作为草图)

     第一步   标记处立方体的各个顶点的坐标位置以及顶点索引如下图:

第二步  :设置三角形顶点顺序,顺时针设置(六个面一共12个三角形)

(一)、首先我们先用代码实现渲染正面Front:

正面可以分为两个三角形

新建脚本,命名DrawCube并将其托给空物体CreateCube如下:

脚本内容(只渲染正面):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshRenderer),typeof(MeshFilter))]
public class DrawCube : MonoBehaviour {
    public Material mat;	
	void Start () {
        DrawCubeObject();
    }
    void DrawCubeObject()
    {
        gameObject.GetComponent<MeshRenderer>().material = mat;
        Mesh mesh = GetComponent<MeshFilter>().mesh;
        mesh.Clear();
        //按照预设的顶点索引值(从0到7) 设置mesh中的顶点数组信息
        //设置顶点索引值是不分顺逆时针的
        mesh.vertices = new Vector3[]
        {   new Vector3(0, 0, 0),
            new Vector3(1, 0, 0),
            new Vector3(1, 1, 0),
            new Vector3(0, 1, 0),
            new Vector3(0, 1, 1),
            new Vector3(1, 1, 1),
            new Vector3(1, 0, 1),
            new Vector3(0, 1, 0),
        };
        //设置三角形顶点顺序,顺时针设置
        mesh.triangles = new int[]
        {
        3, 2, 0,//0,3,2或者2,0,3都可以
        2, 1, 0,//1,0,2或者0,2,1都可以   
       //正面两个三角形渲染出来的就是立方体的正面

        };
    }
}

 

(二)接着实现左面,左侧面同样也是两个三角形: 

 

同理还有其他面后期会补上,先占个坑

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值