工具 unity2018.4.2、 vs017
前述:项目中有时候会遇到模型的中心点与实际中心点有很大偏移,如下图所示:
这时候就需要通过修改模型网格来实现更改中心点,当前也可以找建模的同事帮忙
一、更改后的结果,如下
center与pivot都是一个点,并且模型的位置也没有变
二、代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//重置网格中心点
public class ResetModelPivot : MonoBehaviour
{
#region 字段
public GameObject Model;
Button m_resetBtn;
#endregion
void Start()
{
m_resetBtn = transform.Find("ResetBtn").GetComponent<Button>();
m_resetBtn.onClick.AddListener(() => { MyResetModelPivot(); });
}
//模型pivot与center在一个位置
void MyResetModelPivot()
{
//获得模型的中心
Vector3 center = Model.GetComponent<MeshCollider>().sharedMesh.bounds.center;
Mesh mesh = Model.GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
//网格顶点是本地坐标
for (int i = 0; i < vertices.Length; i++)
{
vertices[i] -= center;
}
mesh.vertices = vertices;
mesh.RecalculateBounds();
mesh.RecalculateTangents();
Model.GetComponent<MeshFilter>().mesh = mesh;
Destroy(Model.GetComponent<MeshCollider>());
Model.AddComponent<MeshCollider>();
}
}
三、脚本挂载
四、资源
资源地址:https://github.com/huangyuanyuan666/ResetModelPivot.git