gpt4 book ai didi

javascript - three.js:如何判断 Vector3 是否在相机的视野内?

转载 作者:行者123 更新时间:2023-12-05 03:11:11 27 4
gpt4 key购买 nike

使用 three.js,是否有一种快速且廉价的方法来检查点/Vector3 是否在相机的视野内?

我希望创建一个盒子网格来填充场景的“地板”,但仅限于不会平移或旋转的可见区域的边缘(或者至少每个盒子的原点在剩饭剩菜卡在视线之外的可见区域)。作为奖励,限制盒子可以“居住”的相机位置的深度也可能很好。

虽然我目前无法找到明确的答案,但可能只是因为缺少找到正确答案所需的正确术语。欢迎澄清和举个简单的例子。

起始代码:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

var vec = new THREE.Vector3(0, 0, 10);

//??? How to tell if Vector3 is within camera's view?

var renderer = new THREE.WebGLRenderer();
document.body.appendChild( renderer.domElement );

console.log('Yes it is just a black/blank screen at this point.');
body { margin: 0; }
canvas { width: 100%; height: 100% }
<html>
<head>
<meta charset=utf-8>
<title>Spot the Vector</title>
</head>
<body>
<script src="https://raw.githubusercontent.com/mrdoob/three.js/master/build/three.min.js"></script>
</body>
</html>

最佳答案

采用 this answer 中所述的相机平截头体

然后,调用

if(frustum.containsPoint( vec ))  
{ ...

编辑:基于上述问题的完整更新示例:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

//var vec = new THREE.Vector3(0, 0, 10); //behind camera
var vec = new THREE.Vector3(0, 0, -10); //in front of camera

//check if within camera's view:
camera.updateMatrix(); // make sure camera's local matrix is updated
camera.updateMatrixWorld(); // make sure camera's world matrix is updated
camera.matrixWorldInverse.getInverse( camera.matrixWorld );

var frustum = new THREE.Frustum();
frustum.setFromMatrix( new THREE.Matrix4().multiply( camera.projectionMatrix, camera.matrixWorldInverse ) );

if(frustum.containsPoint(vec)) {
console.log('within camera view');
} else {
console.log('outside camera view');
}

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
body { margin: 0; }
canvas { width: 100%; height: 100% }
<html>
<head>
<meta charset=utf-8>
<title>Spot the Vector</title>
</head>
<body>
<script src="https://raw.githubusercontent.com/mrdoob/three.js/master/build/three.min.js"></script>
</body>
</html>

关于javascript - three.js:如何判断 Vector3 是否在相机的视野内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37820715/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com