使用透视相机和使用正交相机设置的2D HUD,我在3D场景中有物体(很远):
this.scene = new THREE.Scene();
this.hud = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera( 30, aspect, front, back );
this.camera.position.set(0,0,0);
this.hudCamera = new THREE.OrthographicCamera (-this.windowHalfX,this.windowHalfX, this.windowHalfY, -this.windowHalfY, 1, 10);
this.hudCamera.position.set(0,0,10);
这是我的渲染循环:
updateFrame : function () {
this.renderer.clear();
this.renderer.render( this.scene, this.camera );
this.renderer.clearDepth();
this.renderer.render( this.hud, this.hudCamera );
},
如何使用3D场景中的对象找到HUD中对象的位置?
为了找到一个3D对象的2D HUD位置(使用three.js所版本R71),你可以做到以下几点,我从修改这篇文章:
findHUDPosition : function (obj) {
var vector = new THREE.Vector3();
obj.updateMatrixWorld();
vector.setFromMatrixPosition(obj.matrixWorld);
vector.project(this.camera);
vector.x = ( vector.x * this.windowHalfX );
vector.y = ( vector.y * this.windowHalfY );
return {
x: vector.x,
y: vector.y,
z: vector.z
}
}
该参数obj
是您要在平铺中查找位置的对象。
vector.project(this.camera);
this.camera
通过near
相机的平面从对象绘制矢量到的位置。
vector
的分量的新值是投影向量和this.camera
的近平面的交点。
坐标虽然在three.js的世界坐标系中,所以我们必须快速转换为像素坐标,以放大到画布的大小。
vector.x = ( vector.x * this.windowHalfX );
vector.y = ( vector.y * this.windowHalfY );
上面的转换是针对HUD坐标系在屏幕中心具有原点(0,0),并且最大值是画布分辨率的一半的设置。例如,如果您的画布是1024 x 768像素,则右上角的位置将是(512,384)。
对于典型的屏幕坐标系,右下角为(1024,768),屏幕中间为(512,384)。有此设置,您可以使用下面的转换,如在这个岗位。
vector.x = ( vector.x * widthHalf ) + widthHalf;
vector.y = - ( vector.y * heightHalf ) + heightHalf;
注意,因为我们处于2D状态,所以z坐标现在不再重要。
您要做的最后一件事是确保您要在2D中显示的对象实际上对透视相机可见。这就像检查对象是否落在的视锥中一样简单this.camera
。以下代码的来源
checkFrustrum : function (obj) {
var frustum = new THREE.Frustum();
var projScreenMatrix = new THREE.Matrix4();
this.camera.updateMatrix();
this.camera.updateMatrixWorld();
projScreenMatrix.multiplyMatrices( this.camera.projectionMatrix, this.camera.matrixWorldInverse );
frustum.setFromMatrix( new THREE.Matrix4().multiplyMatrices( this.camera.projectionMatrix,
this.camera.matrixWorldInverse ) );
return frustum.containsPoint ( obj.position );
}
如果不这样做,则可以将位于摄像机后面的对象注册为在2D场景中可见(这会给对象跟踪带来麻烦)。更新obj
的matrix和matrix world也是一个好习惯。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句