19

When working with a 2d canvas, if you want to check if something is no longer "on screen" you simply do something like this:

if( pos.x > window.innerWidth || pos.x < 0 ||
    pos.y > window.innerHeight || pos.y < 0 ) {
    // has left the screen
}

How would I check to see if something is still "on screen" ( in view of the camera ) in a three.js scene?

Nick Briz
  • 1,917
  • 3
  • 20
  • 34

2 Answers2

29

Instead of check 2d canvas, you can check a 3d point is in frustum or not.

camera.updateMatrix();
camera.updateMatrixWorld();
var frustum = new THREE.Frustum();
frustum.setFromMatrix(new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));  

// Your 3d point to check
var pos = new THREE.Vector3(x, y, z);
if (frustum.containsPoint(pos)) {
    // Do something with the position...
}
congle
  • 546
  • 6
  • 11
7
const frustum = new THREE.Frustum()
const matrix = new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
frustum.setFromProjectionMatrix(matrix)
if (!frustum.containsPoint(obj.position)) {
    console.log('Out of view')
}

Use this in a tick function so it will update you when the obj goes out of camera view.

Note: setFromMatrix() is changed to setFromProjectionMatrix() in newer versions of three.js

raghav-wd
  • 410
  • 4
  • 12
  • 2
    This is more up to date than @congle's answer. – Ben Jan 11 '22 at 19:03
  • 1
    I tried to edit the original answer accordingly, but apparently 'the edit queue is full'. StackOverflow leaves so much to be desired these days. – PeterT Jan 11 '23 at 10:50