14

I have been developing an app with three.js but I have encountered this problem and I cannot seem to find any solution to it. I want to determine which meshes are visible right now according to where the camera is currently aiming, so i can refresh my objects (data is coming from a service) or not depending on if they are being shown on the viewport.

I'm using THREE.js in CANVAS mode (I have found a solution using WebGL that says if objects are rendered or not, but i need CANVAS for this project).

I have been trying to find if three.js sets somehow a property to indicate whether the object is visible or not (currently on the screen, not on the entire 3D world), but I can't find it. Meshes have a visible: property but it's always on true even if the camera is not aiming to that object.

Julian
  • 171
  • 2
  • 10

1 Answers1

25

This is the code you're after:

var frustum = new THREE.Frustum();
var cameraViewProjectionMatrix = new THREE.Matrix4();

// every time the camera or objects change position (or every frame)

camera.updateMatrixWorld(); // make sure the camera matrix is updated
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
cameraViewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
frustum.setFromMatrix( cameraViewProjectionMatrix );

// frustum is now ready to check all the objects you need

console.log( frustum.intersectsObject( object ) );
mrdoob
  • 19,334
  • 4
  • 63
  • 62
  • im trying the code but im getting "undefined method" with cameraViewProjectionMatrix.multiplyMatrices, do you know why? was your intent to use .multiply(a, b) ? thanks. – Julian Jul 15 '13 at 13:30
  • 1
    Oh nonono, my bad. Using old version of three.js (rev 54). I'll update. – Julian Jul 15 '13 at 13:40
  • 1
    Will this work with a specific triangle/face? How could it be referenced? – Jack Feb 18 '14 at 22:07
  • Works great for me thanks! Now how can I move an object from any vector outside the frustum to the opposite side of the frustum (goal: respawn the object there after it moves out of view). Question created here: http://stackoverflow.com/questions/25826091/trying-to-respawn-an-object-frustum-intersectsobject-not-working-in-while-loop – ABCD.ca Sep 13 '14 at 18:07
  • I'm getting an "Uncaught TypeError: Cannot read property 'elements' of undefined" when using this? Has this been outdated or something (r71)? – Mobilpadde May 25 '15 at 15:12
  • I was having a strange problem detecting fake intersections (with elements that in fact are not visible in the viewport) and applying this function to check it worked perfectly. Thanks! – spacorum Dec 14 '18 at 22:12