Bereshchenko Yurii
Bereshchenko Yurii

Reputation: 63

How to get all objects that are visible on the camera in Three.js

I need lazy load textures to my meshes, and load only those that are visible to the camera. how i can do this without million vectors in Raycaster?

Upvotes: 6

Views: 2218

Answers (2)

TheJim01
TheJim01

Reputation: 8896

One option is to use a Frustum.

Configure the frustum from the camera by using Frustum.setFromProjectionMatrix:

const frustum = new THREE.Frustum().setFromProjectionMatrix( new THREE.Matrix4().multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ) );

Once you have your frustum, loop through your scene objects to see if they are contained within:

const visibleObjects = []
yourScene.traverse( node => {
  if( node.isMesh && ( frustum.containsPoint( node.position ) || frustum.intersectsObject( node ) ){
    visibleObjects.push( node )
  }
} )

Another (much harder) option is to use GPU picking to identify objects based on an ID color assigned when rendering them. This option is quite involved, so you should probably try the frustum approach first to see if it satisfies what you want to do.

Upvotes: 7

Patryk Janik
Patryk Janik

Reputation: 2623

scene.traverseVisible(callback) 

More info: https://threejs.org/docs/#api/en/core/Object3D.traverseVisible

Upvotes: 0

Related Questions