tap-to-place.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334
  1. AFRAME.registerComponent('tap-to-place', {
  2. init() {
  3. this.raycaster = new THREE.Raycaster()
  4. this.camera = document.getElementById('camera')
  5. this.threeCamera = this.camera.getObject3D('camera')
  6. this.ground = document.getElementById('ground')
  7. document.querySelector('#tap-to-place-cursor').setAttribute('visible', 'true')
  8. // 2D coordinates of the raycast origin, in normalized device coordinates (NDC)---X and Y
  9. // components should be between -1 and 1. Here we want the cursor in the center of the screen.
  10. this.rayOrigin = new THREE.Vector2(0, 0)
  11. this.cursorLocation = new THREE.Vector3(0, 0, 0)
  12. this.onTap = this.onTap.bind(this)
  13. this.el.sceneEl.addEventListener('touchstart', this.onTap)
  14. },
  15. remove() {
  16. this.el.sceneEl.removeEventListener('touchstart', this.onTap)
  17. },
  18. tick() {
  19. this.raycaster.setFromCamera(this.rayOrigin, this.threeCamera)
  20. const intersects = this.raycaster.intersectObject(this.ground.object3D, true)
  21. if (intersects.length > 0) {
  22. const [intersect] = intersects
  23. this.cursorLocation = intersect.point
  24. }
  25. this.el.object3D.position.y = 0.1
  26. this.el.object3D.position.lerp(this.cursorLocation, 0.4)
  27. this.el.object3D.lookAt(this.threeCamera.position.x, this.el.object3D.position.y, this.threeCamera.position.z)
  28. },
  29. onTap() {
  30. document.querySelector('#tap-to-place-cursor').setAttribute('visible', 'false')
  31. this.el.emit('placed')
  32. this.el.removeAttribute('tap-to-place')
  33. },
  34. })