I need an idea. I use the following code to find all the objects in the visible area of the screen in the scene, but it has a problem. It will find all the objects behind the wall, and the objects behind the wall need to be removed.
const vector = new THREE.Vector3(x, y, z)
const v = vector.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
if ((Math.abs(v.x) > 1) || (Math.abs(v.y) > 1) || (Math.abs(v.z) > 1)) {
// 在视野外了
} else {
// 在视野内
}
For a raycaster you can set what objects to check. So, if you know what objects are in front of the wall, put them in an array and give it to the raycaster.
If you don’t know what objects are in front of the wall (e.g. they are moving continuously), then find all intersections (as you do now), but inspect the resulting array of intersections – pick only the beginning of the array up to the wall. This should work, because the array of intersection is sorted from nearest to most distant. So the first entries in the array will be objects in front of the wall, then it will be the wall, and after it will be all objects behind the wall.
thank you for your reply. What I need now is not to click, but to detect when the camera is turned. This is based on screen detection. Do I need to send many rays to detect?
Thank you, I seem to have an idea. Every time I turn the camera, I will send a Raycaster. Get the coordinates of the wall, and then I use this coordinate comparison to calculate the coordinate distance of all objects in the scene
Here is a demo with a fixed wall (white spheres are from this side of the wall, black spheres are from the other side, use the mouse to rotate the scene):
I see. So, here is a demo with raycasting (visibility is checked after camera change). Black spheres are hidden behind the wall, white spheres are visible:
Using Pavel Boytchev’s solution, 1,2,3,4,5 are nicely removed. Now I have a question. When I look in the direction of 6, the camera is at the position of 8, and 9 is also calculated. Expect 9 to be eliminated
I tried the following code,
function transPosition(position) {
const worldVector = new THREE.Vector3(position.x, position.y, position.z)
const vector = worldVector.project(this.camera)
const halfWidth = window.innerWidth / 2
const halfHeight = window.innerHeight / 2
return {
x: Math.round(vector.x * halfWidth + halfWidth),
y: Math.round(-vector.y * halfHeight + halfHeight),
}
}
for (let i = 0; i < objList.length; i++) {
const { x, y } = transPosition(objList[i].position)
if(x > 0 && < window.innerWidth && y > 0 && y window.innerHeight ){
// but 9 is still here
}
}