如何防止这两个立方体同时被拖动?

时间:2016-07-19 08:19:21

标签: javascript three.js aframe

以下是一个拖动示例:https://codepen.io/alexcheninfo/pen/vKkgkE。如果您将一个立方体放在另一个立方体的顶部并抓住前面的立方体,则也会拖动背面的立方体。

这里是完整的代码:

<script>
  AFRAME.registerComponent('draggable', {
    init() {
      this.mouse = new THREE.Vector2();
      this.scene = this.el.sceneEl;
      this.camera = this.scene.camera;
      this.obj = this.el.object3D;

      this.scene.addEventListener('mousemove', e => {
        this.mouse.x = (e.offsetX / this.scene.canvas.offsetWidth) * 2 - 1;
        this.mouse.y = -(e.offsetY / this.scene.canvas.offsetHeight) * 2 + 1;

        if (this.selected) {
          let r = new THREE.Raycaster();
          r.setFromCamera(this.mouse, this.camera);
          let dist = this.obj.position.distanceTo(this.camera.position);
          let point = r.ray.direction.multiplyScalar(dist);
          this.el.setAttribute('position', `${point.x} ${point.y} ${point.z}`);
        }
      });

      this.scene.addEventListener('mousedown', e => {
        let r = new THREE.Raycaster();
        r.setFromCamera(this.mouse, this.camera);
        let intersected = r.intersectObject(this.el.object3D, true);
        let objPos = this.el.object3D.position;
        let camPos = this.camera.position;
        console.log(objPos.distanceTo(camPos));
        if (intersected.length) this.selected = true;
      });

      this.scene.addEventListener('mouseup', e => {
        this.selected = undefined;
      });
    }
  });
</script>

<a-scene>
  <a-entity camera look-controls></a-entity>
  <a-sky src="https://raw.githubusercontent.com/aframevr/aframe/master/examples/boilerplate/panorama/puydesancy.jpg"></a-sky>
  <a-box color="tomato" position="-3 0 -10" draggable></a-box>
  <a-box draggable position="3 0 -5" draggable></a-box>
</a-scene>

如何防止这种情况? (例如,只能在前面拖动立方体?)

1 个答案:

答案 0 :(得分:2)

这是因为您放置控件的位置。你正在做许多射线到一个摄像机,而不是一个raycaster到多个对象。如果你有一个raycaster知道它相交的所有东西(它会返回按距离排序的对象),这会更容易。 http://threejs.org/docs/api/core/Raycaster.html

我将如何构建它:

  • 使用内置raycaster组件。即将与0.3.0一起发布的主分支上的那个具有改进的API。 https://aframe.io/docs/master/components/raycaster.html
  • 拥有一个依赖于raycaster组件的拖动器组件。
  • 让拖动器组件仅与具有draggable组件,draggable类或data-draggable属性的对象相交。

<a-scene> <a-camera> <a-entity dragger></a-entity> </a-camera> <a-entity draggable></a-entity> </a-scene>

AFRAME.registerComponent('dragger', {
  init: function () {
    // Configure raycaster.
    this.el.setAttribute('raycaster', {
      objects: '[draggable]',
      // ...
    });
  },

  tick: function () {
    // Use this.el.components.raycaster.intersectedEls
  }
});