Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity: Wrap mesh softly around other mesh?

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

like image 286
Philipp Lenssen Avatar asked Oct 23 '25 16:10

Philipp Lenssen


1 Answers

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

like image 115
Philipp Lenssen Avatar answered Oct 25 '25 04:10

Philipp Lenssen