【问题标题】:Three.js 2D X, Y coords to 3D X, Y, Z coords always in front of cameraThree.js 2D X、Y 坐标到 3D X、Y、Z 坐标始终在相机前面
【发布时间】:2014-05-30 13:29:03
【问题描述】:

我看过这个问题:

Mouse / Canvas X, Y to Three.js World X, Y, Z

并且已经在我的代码中实现了它,问题是我似乎无法像其他人所说的那样让它工作。

我需要通过 X 和 Y 屏幕坐标在相机前面放置一个对象,而不一定是通过鼠标。

此对象将位于相机前方的指定距离处,可以是预定义的最大距离,也可以是计算的对象距离。

注意:我的相机可以位于场景中的任何位置并面向任何方向

这是我的代码:

this.reticlePos.x = 500;
this.reticlePos.y = 300;
this.reticlePos.z = 0.5;

this.projector.unprojectVector(this.reticlePos, this.camera);

//check for collisions, if collisions set distance to collision distance
var distance = this.RETICLE_RADIUS;

var direction = new THREE.Vector3( 0, 0, -1 );
direction.applyQuaternion( this.camera.quaternion );

this.rayCaster.set(this.camera.position, direction);
var collisionResults = this.rayCaster.intersectObjects(this.sceneController.obstacles);

if( collisionResults.length !== 0 ) {
    // console.log('Ray collides with mesh. Distance :' + collisionResults[0].distance);
    distance = collisionResults[0].distance - 20;
}

// set the reticle position
var dir = this.reticlePos.clone().sub( this.camera.position ).normalize();

var pos = this.camera.position.clone().add( dir.multiplyScalar( distance ) );

this.reticleMesh.position.copy( pos );

如您所见,这与链接的问题非常相似,但我看不到相机前的物体。

任何对此的见解将不胜感激。

【问题讨论】:

    标签: javascript camera three.js projection


    【解决方案1】:

    我自己为以后检查此问题的任何人想出了答案。

    为了获得我的屏幕坐标,我需要从陀螺仪转换一些输入数据,但没有意识到我仍然需要对我计算的屏幕坐标执行以下操作:

    this.reticlePos.x = ( this.reticlePos.x / window.innerWidth ) * 2 - 1;
    this.reticlePos.y = - ( this.reticlePos.y / window.innerHeight ) * 2 + 1;
    

    执行此操作后,一切都按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 2010-10-16
      • 2014-12-02
      • 1970-01-01
      相关资源
      最近更新 更多