Given one mesh (like the cubic object on the left) and another custom sphere-like mesh (on the right; it could be another shape if easier), how would one in Unity & C# durin
The following approach, with thanks to VirtualMethodStudio for the pointer, takes a wrapper sphere which then for each vertice in it casts a ray inwards, and adjusts that vertex to the hit point:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShrinkWrapSphere : MonoBehaviour {
void Start() {
Debug.Log("Starting...");
MeshFilter meshFilter = gameObject.GetComponent();
Mesh mesh = meshFilter.mesh;
Vector3[] vertices = new Vector3[mesh.vertices.Length];
System.Array.Copy(mesh.vertices, vertices, vertices.Length);
for (int i = 0; i < vertices.Length; i++) {
Vector3 rayDirection = -mesh.normals[i];
RaycastHit hit;
if ( Physics.Raycast( vertices[i], rayDirection, out hit, 100f ) ) {
vertices[i] = hit.point * 2f;
}
else {
vertices[i] = Vector3.zero;
}
}
mesh.vertices = vertices;
Debug.Log("Done. Vertices count " + vertices.Length);
// mesh.RecalculateBounds();
// mesh.RecalculateNormals();
// mesh.RecalculateTangents();
}
}
The resulting mesh can then furthermore be simplified via the Simplify function of this asset.
An alternative to above is to use Collider.ClosestPoint(vertexPoint).