Skip to content

Instantly share code, notes, and snippets.

@klaszlo8207
Last active January 18, 2023 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klaszlo8207/a66d5c7c2efa81919c59629804a6fa6f to your computer and use it in GitHub Desktop.
Save klaszlo8207/a66d5c7c2efa81919c59629804a6fa6f to your computer and use it in GitHub Desktop.
using System;
using UnityEngine;
namespace _MyScripts.Utils
{
public static class MeshExtensions
{
public static Mesh PivotToCenter(this Mesh originalMesh)
{
var mesh = new Mesh();
mesh = originalMesh;
var minX = float.MaxValue;
var minY = float.MaxValue;
var minZ = float.MaxValue;
var maxX = float.MinValue;
var maxY = float.MinValue;
var maxZ = float.MinValue;
//var shifts = new Vector3[mesh.vertexCount];
//var firstVertex = mesh.vertices[0];
for (var i = 0; i < mesh.vertexCount; i++)
{
var v = mesh.vertices[i];
if (v.x > maxX) maxX = v.x;
if (v.y > maxY) maxY = v.y;
if (v.z > maxZ) maxZ = v.z;
if (v.x < minX) minX = v.x;
if (v.y < minY) minY = v.y;
if (v.z < minZ) minZ = v.z;
//shifts[i] = firstVertex - v;
}
var size = new Vector3(
Math.Abs(minX) + maxX,
Math.Abs(minY) + maxY,
Math.Abs(minZ) + maxZ
);
var center = size / 2;
var newVertices = new Vector3[mesh.vertexCount];
for (var i = 0; i < mesh.vertexCount; i++)
{
var v = mesh.vertices[i];
v -= center; // firstVertex;
newVertices[i] = v;
}
mesh.SetVertices(newVertices);
//Debug.Log(size + " " + center + " " + firstVertex + " - " + newVertices.First());
return mesh;
}
public static Mesh PivotToCenterPoint(this Mesh originalMesh, Vector3 centerPoint)
{
var mesh = new Mesh();
mesh = originalMesh;
var minX = float.MaxValue;
var minY = float.MaxValue;
var minZ = float.MaxValue;
var maxX = float.MinValue;
var maxY = float.MinValue;
var maxZ = float.MinValue;
for (var i = 0; i < mesh.vertexCount; i++)
{
var v = mesh.vertices[i];
if (v.x > maxX) maxX = v.x;
if (v.y > maxY) maxY = v.y;
if (v.z > maxZ) maxZ = v.z;
if (v.x < minX) minX = v.x;
if (v.y < minY) minY = v.y;
if (v.z < minZ) minZ = v.z;
}
var newVertices = new Vector3[mesh.vertexCount];
for (var i = 0; i < mesh.vertexCount; i++)
{
var v = mesh.vertices[i];
v -= centerPoint;
newVertices[i] = v;
}
mesh.SetVertices(newVertices);
return mesh;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment