Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js - How to check if an object is visible to the camera

I'm having hard times figuring out what's the best way to check if a Object3d is visible for the eyes of the camera.

I'm having a sphere in the middle of the screen. Some cubes are added on it's surface randomly. What I would need is a way to check which cubes are visible (on the front half of the sphere) and which one are invisible (on the back half of the sphere) for the eyes of the camera.

What I have found so far seems to be the right direction - but I must be missing something with the THREE.Raytracer class.

Here is a fiddle of the code that I'm using: jsfiddle. I have tried to make it as clear as possible.

This part of the fiddle might contain the buggy code:

var raycaster = new THREE.Raycaster();
var origin = camera.position, direction, intersects, rayGeometry = new THREE.Geometry(), g;
pointGroup.children.forEach(function(pointMesh) {
    direction = pointMesh.position.clone();
    // I THINK THIS CALCULATION MIGHT BE WRONG - BUT DON'T KNOW HOW TO CORRECT IT
    raycaster.set(origin, direction.sub(origin).normalize());
    // if the pointMesh's position is on the back half of the globe, the ray should intersect with globe first and the hit the point as second target - because the cube is hidden behind the bigger sphere object
    intersects = raycaster.intersectObject(pointMesh);
    // this is always empty - should contain objects that are located on the back of the sphere ...
    console.log(intersects);
}); 

Frustum Culling is not working as outlined in this stack overflow question here: post1

Also this post2 and this post3 are explaining the topic really good but not quite for this situation.

Thank you for you help!

like image 541
hetsch Avatar asked Mar 11 '14 08:03

hetsch


2 Answers

You want to look at Occlusion Culling techniques. Frustum culling works fine and is not what you are describing. Frustum culling just checks if an object (or its bounding box) is inside the camera pyramid. You perform Occlusion culling in addition to Frustum Culling specially when you want to eliminate objects which are occluded by other objects inside the view frustum. But it is not an easy task.

like image 85
gaitat Avatar answered Sep 23 '22 05:09

gaitat


I just worked though a similar problem where I was trying to detect when a point in world space passed out of view of the camera and behind specific objects in the scene. I created a jsfiddle, (see below) for it. When the red "target" passes behind any of the three "walls" a blue line is drawn from the "target" to the camera. I hope this helps.

like image 1
user3889022 Avatar answered Sep 21 '22 05:09

user3889022