Three.js屏幕坐標轉3d坐標

在網(wǎng)上找了好久,終于功夫不負有心人。終于被我找到了。哈哈!
附上原文鏈接:
https://stackoverflow.com/questions/13055214/mouse-canvas-x-y-to-three-js-world-x-y-z
實現(xiàn)代碼:

/**
 * 
 * @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;
},

代碼解釋,網(wǎng)上復制過來的
原文鏈接
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);
},

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

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 我開始寫作的緣由,是大兒子的老師每次布置作文作業(yè),他都索性不寫要么寫上幾句幼稚如小學生的話。有次逼的...
    flyboy168閱讀 370評論 4 4
  • 長達半個月的高強度體力透支,讓他幾近虛脫。還好,這份需要透支體力的“工作”終于告一段落。用茍延殘喘來形容此時此刻的...
    雪候玄鳥閱讀 584評論 0 3
  • 《自古多少圣》 作者:唐朝寒山 自古多少圣,叮嚀教自信。 人根性不等,高下有利鈍。 真佛不肯認,置功枉受困。 不知...
    shiny茜茜閱讀 903評論 0 0
  • 一一觀交通事故圖片有感 一輛車與另一輛車 相對著 疾馳而過 為了提前抵達各自的終點 彼此都沒有半點停留 兩輛車看...
    哦小巷閱讀 240評論 0 4
  • 三月份開始畫彩鉛的,斷斷續(xù)續(xù)差不多快一個月了,一直想著有機會也寫個教程,但是一直拖拖拉拉。今天就只好逼自己一...
    懵橙閱讀 2,139評論 7 4

友情鏈接更多精彩內(nèi)容