Skip to content

Instantly share code, notes, and snippets.

@superstes
Created April 7, 2024 14:37
Show Gist options
  • Save superstes/4f11649ff089b45a29bc44f147c226c2 to your computer and use it in GitHub Desktop.
Save superstes/4f11649ff089b45a29bc44f147c226c2 to your computer and use it in GitHub Desktop.
ThreeJS - Check if point is in front of camera (inside FOV)
/*
NOTES:
basic source: https://discourse.threejs.org/t/detect-if-target-is-behind-the-camera-bis/219/2
you could also use a frustum: https://threejs.org/docs/index.html#api/en/math/Frustum.containsPoint
we assume the InFrontOfCamera will be called many times each frame - so we want to prepare the camera values it uses to lower processing cost
*/
const CAM_FOV = 60;
const CAM_FOV2 = (Math.PI / 360) * (360 - CAM_FOV);
function inFrontOfCamera(cameraPosition, cameraDirection, position) {
let p = new THREE.Vector3();
p.copy(position);
return (p.sub(cameraPosition).angleTo(cameraDirection)) < (Math.PI / CAM_FOV2);
}
const aspect = 1920 / 1080;
const near = 1;
const far = 25000.0;
const camera = new THREE.PerspectiveCamera(CAM_FOV, aspect, near, far);
cameraDirection = new THREE.Vector3();
// each frame
camera.getWorldDirection(cameraDirection);
let testPoint = new THREE.Vector3(1, 1, 1);
if (inFrontOfCamera(camera.position, cameraDirection, testPoint)) {
// do stuff
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment