2
votes

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
where does the z = -1 comes from ?Caillou

1 Answers

3
votes

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)
    })
  }
});