Unity: Wrap mesh softly around other mesh?

前端 未结 1 527
感情败类
感情败类 2021-02-06 18:19

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

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 18:34

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

    0 讨论(0)
提交回复
热议问题