我有一个three.js场景,想知道视口的3D边界。
例如,我们说我的画布宽500像素,高1000像素。我的相机正在查看位置{ 0, 0, 0 }
,位于{ 0, 0, 100 }
;
我的相机永远不动。
我们说我的对象位于{ 0, 0, 0 }
。我需要能够将该对象移动到可视区域内的各个点(在摄像机视野内)。我怎样才能计算出相机视场的上/左角?另外,我怎样才能从左边算起20%,从相机顶部看下来10%?
这是我的相机对象:
{
"object": {
"uuid": "E26C5F88-CD17-45F8-A492-F3DD704949BF",
"type": "PerspectiveCamera",
"matrix": [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 100, 1],
"zoom": 1,
"fov": 50,
"aspect": 0.625,
"near": 0.1,
"far": 1000
}
}
答案 0 :(得分:5)
要将对象从左侧放置20%,从顶部放置10%,您可以使用以下内容:
var left = 0.2;
var top = 0.1;
var depth = 0.7; // from -1 to 1, depends how far into the scene you want the object, -1 being very close, 1 being the furthest away the camera can see
object.position.set( -1 + 2 * left, 1 - 2 * top, depth ).unproject( camera );
这会将位于NDC(标准化设备坐标)的位置转换为世界坐标,这些位置都在[-1,1]范围内。
它基本上与下面的图像(source)相反,并将右图像(NDC)中的一个点转换回左图像(世界坐标):
例如:
var canvas = document.getElementById('canvas');
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true});
var camera = new THREE.PerspectiveCamera(45, canvas.clientWidth / canvas.clientWidth, 1, 1000);
var clock = new THREE.Clock();
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({color: '#f00', wireframe: true});
var box = new THREE.Mesh(geometry, material);
scene.add(box);
var period = 5;
var top = 0.3; // 30%
var left = 0.2; // 20%
var depth = 0.7;
render();
function render() {
requestAnimationFrame(render);
if (canvas.width !== canvas.clientWidth || canvas.height !== canvas.clientHeight) {
renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
box.position.set(-1 + 2 * left, 1 - 2 * top, depth).unproject(camera);
box.rotation.y += clock.getDelta() * 2 * Math.PI / period;
renderer.render(scene, camera);
}
html, body, canvas {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: block;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r73/three.min.js"></script>
<canvas id="canvas"></canvas>