Search code examples
3dthree.jsfrustum

ThreeJs: Check if Object is in center of Camera


I'd like to check if a cylinder is more or less in the middle of the camera to perform an interaction then. The cylinder operates like a button. My idea was to check with the frustum, but I have no idea, how to adjust the z-axis. Or may they be a better option?

var frustum = new THREE.Frustum();
var matrix = new THREE.Matrix4().multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
frustum.setFromMatrix( matrix );
if(frustum.containsPoint( cylinder.position ))
  cylinder.material.color.setHex( '0xbada55' );
else      
  cylinder.material.color.setHex( '0xffcc00' );

This checks if the cylinder is in view and not, if in the middle range.


Solution

  • Raycasting is expensive.

    The simplest way is to project the cylinder position into screen space and check if it is close to the center of the screen. This way, you can also define a threshold for how close to center it needs to be:

    var threshold = 0.2;
    
    var positionScreenSpace = cylinder.position.clone().project(camera);
    positionScreenSpace.setZ(0);
    
    var isCloseToCenter = positionScreenSpace.length() < threshold;
    

    I have made a demonstration of this here: https://jsfiddle.net/holgerl/z199hzgd/