DEV Community

HandsomeTan
HandsomeTan

Posted on

Three.js: How to determine if a point is inside a box?

Usually, a point's position is in world space. To check if it's inside a box, we need to transform it into the box's local coordinate system. We do this by multiply the point's world coordinates by box's inverse transformation matrix. This matrix converts from world space to the box's local space.

// get the box's inverse transformation matrix
const inverseMatrix = new THREE.Matrix4().copy(box.matrixWorld()).invert();

// transform the point to the box's local space
const localPoint = point.clone().applyMatrix4(inverseMatrix);
Enter fullscreen mode Exit fullscreen mode

After this transformation, we get the point position relative to the box's local coordinates. Then. we simply check if the new local position is within the box's bounding dimensions(comparing against the box's min and max values). If all coordinates(x, y, z) are within the box's bounds, the point is inside.

// get the box's bounding box in local space
const boxGeometry = box.geometry;
boxGeometry.coumputeBoundingBox();
const bbox = boxGeometry.boundingBox;

// check if the point is within bounds
bbox.containsPoint(localPoint);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)