Reputation: 156
I have a case in which I have to know in which direction the object is from camera.
I know how to detect that if the object is in view of camera or not. But for the objects that are not in view of camera, I need to know the direction of them. Like they are nearest in right direction or left.
I have also attached a picture to help understand the situation.
Upvotes: 1
Views: 959
Reputation: 152
You need to calculate the angle between the camera view vector and the vector object.position - camera.position. Then you will know if the objects are to the right or left of the camera view angle.
Camera angle can be retrieved by PerspectiveCamera.getWorldDirection(new THREE.Vector3())
See docs here: https://threejs.org/docs/?q=camera#api/en/cameras/Camera
Psuedocode could be:
let outOfViewObjects = getOutofViewObjects()
let left = []
let right = []
outOfViewObjects.forEach(val => {
let vector1 = camera.position.clone().sub(val.position)
let vector2 = camera.getWorldDirection(new THREE.Vector3())
let angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x)
if(angle < 0) left.push
else right.push
})
let leftCount = left.length
let rightCount = right.length
Upvotes: 1
Reputation: 8896
Convert the object positions to local camera coordinates, then look at the x
value.
// given obj1...
let temp = obj1.position.clone();
camera.worldToLocal( temp );
if( temp.x > 0){
console.log('The object is in the right half of the screen!');
}
else if(temp.x < 0){
console.log('The object is in the left half of the screen!');
}
else{
console.log('The object is in the exact middle!');
}
Now there may be a case where the object's geometry causes its position to be on one side, but the object gets drawn on the opposite side or the center. Detecting that is more complex, but the concept is basically the same, and you could use bounding boxes/spheres to make it easier.
Upvotes: 3