9
\$\begingroup\$

How can I find if a point (Vector3) is inside of a mesh? Would this work for both concave and convex objects? I read somewhere that if you raycast in both directions of every axis (X, -X, Y, -Y, Z, -Z), take the count of the hits, and if it is even it is outside, if it is odd it is inside. I tried this and it didn't work.

\$\endgroup\$
1
  • \$\begingroup\$ Assuming a closed mesh, check the point is overlapping the half planes defined by the surface normals of all faces. A Google search may show a less than O(n^2) algorithm though. \$\endgroup\$ Jul 1, 2012 at 22:53

1 Answer 1

6
\$\begingroup\$

Figured it out.

What you have to do is raycast from your point in any direction you want. Then, count how many times the raycast intersects with your mesh. If the count is an odd number, it is inside of the mesh. If it is even it is outside of it.

Since unity doesn't raycast on inside sides, you have to flip the faces in your 3d authoring tool. Then you have to raycast in the opposite direction to make up for the other side. (I haven't figured out how to get the count of hits from the raycast yet. But I am using a cube right now, which only has 2 perpendicular faces, so it works)

Unity C# code:

bool checkIfInside(Vector3 point) {

    Vector3 direction = new Vector3(0, 1, 0);

    if(Physics.Raycast(point.position, direction, Mathf.Infinity) &&
        Physics.Raycast(point.position, -direction, Mathf.Infinity)) {
            return true;
    }

    else return false;
}
\$\endgroup\$
3
  • \$\begingroup\$ (add: obviously the direction must be longer than the size of the mesh you're testing) \$\endgroup\$
    – Will
    Jul 1, 2012 at 20:24
  • 1
    \$\begingroup\$ Not necessarily. The Raycast method in Unity, has an optional parameter of distance which I set to Mathf.Infinity. \$\endgroup\$ Jul 9, 2012 at 19:04
  • \$\begingroup\$ For anybody interested, a general solution to this is given by PNPOLY ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html \$\endgroup\$ Jun 16, 2014 at 19:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .