public static bool hitObject(Component[] objects, Ray rayWorld, out MeshFilter minMf, out TriangleTester.HitRes minHit) { List<BoundsDistance> mfHitBounds = new List<BoundsDistance>(); foreach (var obj in objects) { var mf = obj.GetComponent<MeshFilter>(); var renderer = obj.GetComponent<Renderer>(); if (!obj.gameObject.activeInHierarchy || mf == null || renderer == null) continue; var bounds = renderer.bounds; float dist; if (!bounds.IntersectRay(rayWorld, out dist)) continue; mfHitBounds.Add(new BoundsDistance(){ mf = mf, distance = dist }); //Debug.Log("Candidate (Bounds) : " + mf.gameObject.name); } mfHitBounds.Sort((x, y) => (x.distance < y.distance ? -1 : 1)); bool found = false; minMf = null; minHit = default(TriangleTester.HitRes); var minDist = Mathf.Infinity; foreach (BoundsDistance mfDists in mfHitBounds) { if (minDist < mfDists.distance) break; MeshFilter mf = mfDists.mf; Vector3 rayOrigin = mf.transform.InverseTransformPoint(rayWorld.origin); Vector3 rayDirection = mf.transform.worldToLocalMatrix * (Vector4) rayWorld.direction; Mesh m = mf.sharedMesh; TriangleTester.HitRes hit; if (!TriangleTester.hitTriangleAll(rayOrigin, rayDirection, m.vertices, m.triangles, out hit)) continue; found = true; var dist = hit.t; if (dist < minDist) { minDist = dist; minHit = hit; minMf = mf; } } return found; }
public static bool hitObject(Component[] objects, Ray rayWorld, out MeshFilter minMf, out TriangleTester.HitRes minHit) { List <BoundsDistance> mfHitBounds = new List <BoundsDistance>(); foreach (var obj in objects) { var mf = obj.GetComponent <MeshFilter>(); var renderer = obj.GetComponent <Renderer>(); if (!obj.gameObject.activeInHierarchy || mf == null || renderer == null) { continue; } var bounds = renderer.bounds; float dist; if (!bounds.IntersectRay(rayWorld, out dist)) { continue; } mfHitBounds.Add(new BoundsDistance() { mf = mf, distance = dist }); //Debug.Log("Candidate (Bounds) : " + mf.gameObject.name); } mfHitBounds.Sort((x, y) => (x.distance < y.distance ? -1 : 1)); bool found = false; minMf = null; minHit = default(TriangleTester.HitRes); var minDist = Mathf.Infinity; foreach (BoundsDistance mfDists in mfHitBounds) { if (minDist < mfDists.distance) { break; } MeshFilter mf = mfDists.mf; Vector3 rayOrigin = mf.transform.InverseTransformPoint(rayWorld.origin); Vector3 rayDirection = mf.transform.worldToLocalMatrix * (Vector4)rayWorld.direction; Mesh m = mf.sharedMesh; TriangleTester.HitRes hit; if (!TriangleTester.hitTriangleAll(rayOrigin, rayDirection, m.vertices, m.triangles, out hit)) { continue; } found = true; var dist = hit.t; if (dist < minDist) { minDist = dist; minHit = hit; minMf = mf; } } return(found); }