4

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# during runtime softly wrap the second mesh around the first? Thanks!

enter image description here

Philipp Lenssen
  • 8,818
  • 13
  • 56
  • 77

1 Answers1

5

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<MeshFilter>();
        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();
    }

}

enter image description here

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).

Philipp Lenssen
  • 8,818
  • 13
  • 56
  • 77