Example #1
0
        /// <summary>
        /// Returns the closest point an a mesh. If cacheKDTree is set to true (default), the kdtree will be cached
        /// so it can be reused later which will greatly improve performance for the sake of RAM usage.
        /// </summary>
        /// <returns>The point on mesh.</returns>
        /// <param name="mesh">Mesh.</param>
        /// <param name="point">Point.</param>
        /// <param name="cacheKDTree">If set to <c>true</c> cache KD tree.</param>
        public static Vector3 ClosestPointOnMesh(MeshCollider mesh, Vector3 point, bool cacheKDTree = true)
        {
            //If object has a mesh KDTree, use it
            MeshKDTree meshKDTree = mesh.GetComponent <MeshKDTree>();

            if (meshKDTree != null)
            {
                return(ClosestPointOnMeshKDTree(meshKDTree, point));
            }

            //Check if we have a KDTree for the supplied mesh
            if (kdTreePool.ContainsKey(mesh.sharedMesh))
            {
                return(kdTreePool[mesh.sharedMesh].FindNearestPointOnMesh(point, mesh.transform));
            }
            else
            {
                //If not, create new KDTree and find closest point
                KDTree  kdTree = KDTree.CreateFromMesh(mesh.sharedMesh);
                Vector3 result = kdTree.FindNearestPointOnMesh(point, mesh.transform);
                //Cache kd tree for later use is user wants to cache it
                if (cacheKDTree)
                {
                    kdTreePool.Add(mesh.sharedMesh, kdTree);
                }
                else
                {
                    kdTree = null;
                }
                return(result);
            }
        }
Example #2
0
 /// <summary>
 /// Returns the closest point on a mesh KDTree.
 /// </summary>
 /// <returns>The vertex on KD mesh.</returns>
 /// <param name="mesh">Mesh.</param>
 /// <param name="point">Point.</param>
 public static Vector3 ClosestPointOnMeshKDTree(MeshKDTree mesh, Vector3 point)
 {
     return(mesh.ClosestPointOnSurface(point));
 }