检查对象在 threejs 中的相机方向
Check in which direction of camera the object is in threejs
我有一个案例,我必须知道物体来自相机的哪个方向。
我知道如何检测物体是否在相机视野中。但是对于不在相机视野内的物体,我需要知道它们的方向。就像他们在右边或左边最近。
我还附上了一张图片,以帮助了解情况。
您需要计算相机视图矢量与矢量 object.position - camera.position 之间的角度。然后你就会知道物体是在相机视角的右边还是左边。
可以通过 PerspectiveCamera.getWorldDirection(new THREE.Vector3())
检索相机角度
在此处查看文档:https://threejs.org/docs/?q=camera#api/en/cameras/Camera
伪代码 可以是:
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
将对象位置转换为本地相机坐标,然后查看 x
值。
// 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!');
}
现在可能会出现对象的几何形状导致其位置在一侧的情况,但对象被绘制在另一侧或中心。检测更复杂,但概念基本相同,您可以使用边界 boxes/spheres 使其更容易。
我有一个案例,我必须知道物体来自相机的哪个方向。
我知道如何检测物体是否在相机视野中。但是对于不在相机视野内的物体,我需要知道它们的方向。就像他们在右边或左边最近。
我还附上了一张图片,以帮助了解情况。
您需要计算相机视图矢量与矢量 object.position - camera.position 之间的角度。然后你就会知道物体是在相机视角的右边还是左边。
可以通过 PerspectiveCamera.getWorldDirection(new THREE.Vector3())
检索相机角度在此处查看文档:https://threejs.org/docs/?q=camera#api/en/cameras/Camera
伪代码 可以是:
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
将对象位置转换为本地相机坐标,然后查看 x
值。
// 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!');
}
现在可能会出现对象的几何形状导致其位置在一侧的情况,但对象被绘制在另一侧或中心。检测更复杂,但概念基本相同,您可以使用边界 boxes/spheres 使其更容易。