Three.js屏幕坐标转3d坐标

在网上找了好久,终于功夫不负有心人。终于被我找到了。哈哈!
附上原文链接:
https://stackoverflow.com/questions/13055214/mouse-canvas-x-y-to-three-js-world-x-y-z
实现代码:

/**
 * 
 * @param {Number} x 屏幕坐标 x
 * @param {Number} y 屏幕坐标 y
 * @param {Document} domContainer 存放元素的容积
 * @param {THREE.PerspectiveCamera} camera 相机
 * @param {Number} targetZ  z轴 默认为0
 */
screenPointToThreeCoords(x, y, domContainer, camera, targetZ) {
  var vec = new THREE.Vector3(); // create once and reuse
  var pos = new THREE.Vector3(); // create once and reuse

  vec.set(
      ( x / domContainer.clientWidth ) * 2 - 1,
      - ( y / domContainer.clientHeight ) * 2 + 1,
      0.5 );

  vec.unproject( camera );

  vec.sub( camera.position ).normalize();

  var distance = (targetZ - camera.position.z) / vec.z;

  pos.copy( camera.position ).add( vec.multiplyScalar( distance ) );
  return pos;
},

代码解释,网上复制过来的
原文链接
https://discourse.threejs.org/t/project-a-2d-screen-point-to-3d-world-point/5713

As I understand,

after the line:
vec.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
vec is the position of a 3D point (pointA) in space along the ray in Normalized Device Coordinates

after the line:
vec.unproject( camera );
vec is the position of pointA in 3D space in world coordinates

after the line:
vec.sub( camera.position ).normalize();
vec is the normalized ray direction from the camera

after the line:
var distance = ( targetZ - camera.position.z ) / vec.z;
distance is the distance/scale by which to travel along the ray, until reaching a point on the ray which lies in plane z=targetZ

after the line:
pos.copy( camera.position ).add( vec.multiplyScalar( distance ) );
pos is the position of the 3D point (pointB) which lies on the ray and is at z==targetZ
最后附上我设置的

this.subRenderer = new THREE.CSS3DRenderer();
this.subCamera = new THREE.PerspectiveCamera(45, this.$subContainer.clientWidth / this.$subContainer.clientHeight, 1, 10000);
this.subScene = new THREE.Scene();
this.subControls = new THREE.TrackballControls(
  this.subCamera,
  this.subRenderer.domElement,
);
// 重新绘制
subRender() {
  this.subRenderer.render(this.subScene, this.subCamera);
},

祝兄弟早日找到自己想要的答案

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我开始写作的缘由,是大儿子的老师每次布置作文作业,他都索性不写要么写上几句幼稚如小学生的话。有次逼的...
    flyboy168阅读 326评论 4 4
  • 长达半个月的高强度体力透支,让他几近虚脱。还好,这份需要透支体力的“工作”终于告一段落。用苟延残喘来形容此时此刻的...
    雪候玄鸟阅读 538评论 0 2
  • 《自古多少圣》 作者:唐朝寒山 自古多少圣,叮咛教自信。 人根性不等,高下有利钝。 真佛不肯认,置功枉受困。 不知...
    shiny茜茜阅读 871评论 0 0
  • 一一观交通事故图片有感 一辆车与另一辆车 相对着 疾驰而过 为了提前抵达各自的终点 彼此都没有半点停留 两辆车看...
    哦小巷阅读 180评论 0 4
  • 三月份开始画彩铅的,断断续续差不多快一个月了,一直想着有机会也写个教程,但是一直拖拖拉拉。今天就只好逼自己一...
    懵橙阅读 2,052评论 7 4