AFRAME screen to world position

只谈情不闲聊 提交于 2019-12-24 08:21:59

问题


I'm trying to convert Mouse position to world coordinates in Three via Aframe

Using something like

let mouse = new three.Vector2()
let camera = document.querySelector('#camera')
let rect = document.querySelector('#sceneContainer').getBoundingClientRect()
mouse.x = ( (event.clientX - rect.left) / rect.width ) * 2 - 1
mouse.y = - ( (event.clientY - rect.top) / rect.height ) * 2 + 1

let vector = new three.Vector3( mouse.x, mouse.y, -1 ).unproject( camera )

However it doesn't seem to be able to handle the camera, I get

TypeError: Cannot read property 'elements' of undefined

From Matrix4.getInverse

9550 | 
 9551 | // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9552 | var te = this.elements,
> 9553 |    me = m.elements,
  9554 | 
  9555 |    n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  9556 |    n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],

I presume it's not reading the camera properly, any ideas on how to get the three camera out of the aframe camera if that's the problem?


回答1:


Using Piotr's info about accessing the camera and fixing up the 'three' to 'THREE' seems to work:

https://glitch.com/edit/#!/aframe-mouse-to-world

AFRAME.registerComponent('mouse-to-world', {
  init: function () {
    document.addEventListener('click', (e) => {
      let mouse = new THREE.Vector2()
      let camera = AFRAME.scenes[0].camera
      let rect = document.querySelector('body').getBoundingClientRect()
      mouse.x = ( (e.clientX - rect.left) / rect.width ) * 2 - 1
      mouse.y = - ( (e.clientY - rect.top) / rect.height ) * 2 + 1
      let vector = new THREE.Vector3( mouse.x, mouse.y, -1 ).unproject( camera )
      console.log(vector)
    })
  }
});


来源:https://stackoverflow.com/questions/48434953/aframe-screen-to-world-position

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!