unity中保存mesh资源和点集txt文档并实现物体镜像

给一个fbx或obj格式的导入物体,另外保存其mesh资源,或者保存其内部的点的STL坐标以供研究。代码挂载到fbx或obj物体上即可,另外此代码可以随机不停地更改物体的顶点坐标形成动画效果(见代码中的update中屏蔽的部分)。物体的镜像需要进行两个操作:顶点Vertices取反和三角面片Triangles的渲染顺序颠倒。RandoMeshmVertices.cs如下:

// RandoMeshmVertices.cs
// 随机修改Mesh顶点坐标

using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

public class RandoMeshmVertices : MonoBehaviour
{
    // Mesh的实例
    MeshFilter meshFilter;

    // 顶点的原始坐标
    Vector3[] originalVertices;

   
    void Start()
    {
        meshFilter = GetComponent<MeshFilter>();
//        string name="test";
//        AssetDatabase.CreateAsset(meshFilter.mesh, "Assets/" + name + ".asset");//mesh可直接保存
        originalVertices = meshFilter.mesh.vertices;
//        originalNornals = meshFilter.mesh.normals;

        Vector3 meshpos = gameObject.transform.GetComponent<MeshFilter>().mesh.bounds.center;
        Debug.Log($"FBX's center is {meshpos}");
        //  根据mesh在fbx模型中的相对坐标(即中心点)获取到绝对世界坐标
        Vector3 mypos = gameObject.transform.TransformPoint(meshpos);
        Debug.Log($"FBX's world coordinate is {mypos}");
        Vector3 meshsize = gameObject.transform.GetComponent<MeshFilter>().mesh.bounds.size;
        Debug.Log($"FBX's size is {meshsize}");       
        string path = Application.dataPath + "stl.txt";
        FileStream fs = File.OpenWrite(path);
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < originalVertices.Length; ++i)
        {
            originalVertices[i].x = -originalVertices[i].x;

            sb.Append(originalVertices[i]);
            //           Debug.Log($"originalVertices are {originalVertices[i]}\n");
            sb.AppendLine();
        }
        byte[] stl = Encoding.UTF8.GetBytes(sb.ToString());
        fs.Write(stl,0,stl.Length);
        fs.Close();
        fs.Dispose();
        //将所有面的顶点渲染顺序颠倒
        int[] backupTriangles = meshFilter.mesh.triangles;
        int[] NewTriangles=new int[backupTriangles.Length];
        for (int i = 0; i < backupTriangles.Length; i++)
        {
            NewTriangles[NewTriangles.Length - i - 1] = backupTriangles[i];
        }
        meshFilter.mesh.vertices = originalVertices;
        meshFilter.mesh.triangles = NewTriangles;
        meshFilter.mesh.RecalculateNormals();

    }

    void Update()
    {
 /*       // 随机修改顶点坐标
        Vector3[] vertices = meshFilter.mesh.vertices;
        for (int i = 0; i < originalVertices.Length; ++i)
        {
            var v = originalVertices[i];
            vertices[i] = v + Random.Range(-1.1F,1.1F) * Vector3.one;
        }
        meshFilter.mesh.vertices = vertices;
        meshFilter.mesh.RecalculateNormals();*/
    }
}

镜像前:

运行后镜像效果

猜你喜欢

转载自blog.csdn.net/weixin_44345862/article/details/127268113
今日推荐