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

Viewed 558

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?

2 Answers

One option is to use a Frustum.

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

const frustum = new THREE.Frustum().setFromProjectionMatrix( camera.projectionMatrix )

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.

Related