THREE.JS:在元素组上激活dragControl后,如何禁用它们?

时间:2019-01-23 10:49:56

标签: javascript three.js

我有一个在按下“ m”键的同时激活dragControls的功能。由于某些原因,当未按下“ m”时,它不会被停用。如何禁用dragControls?

如果语句为true,我试图封装将要激活的dragControls,否则dragControls = null。但是,无论何时第一次激活发生,即使该语句为false,也不会取消激活。 While和do While循环只会冻结浏览器。

  init() {
  // EVENT LISTENERS:
  map.addEventListener('mousedown', this.movePoi, false);
  document.addEventListener('keydown', this.onDocumentKeyDown, false);
  document.addEventListener('keyup', this.onDocumentKeyUp, false);

},

// HELPER FUNCTIONS:
onDocumentKeyDown(event) {

  let keycode = event.which;
  if (keycode === 77) {
    this.moveIt = true;
    this.controls.enabled = false;
    console.log("Key is pressed");
    console.log(this.moveIt);
  }
},
onDocumentKeyUp(event){
  let keycode = event.which;
  console.log(keycode);
  if (keycode === 77) {
    this.moveIt = false;
    this.controls.enabled = true;
    console.log("Key is unpressed");
    console.log(this.moveIt);
  }
},
mouseOverScene (event) {
  event.preventDefault();
  let rect = event.target.getBoundingClientRect();
  let x = event.clientX - rect.left;
  let y = event.clientY - rect.top;

  this.mouse.x = ( x / this.mapWidth) * 2 - 1;
  this.mouse.y = - ( y / this.mapHeight ) * 2 + 1;

  this.rayCaster.setFromCamera(this.mouse, this.camera);
},

//POI movement around the scene:

movePoi (event) {

  event.preventDefault();
  let controlsDrag;
  if (this.moveIt) {
  controlsDrag = new DragControls(this.spheres, this.camera, this.renderer.domElement);

  } else {
    controlsDrag = null;
  }
}

已执行:应在按下“ m”键的同时,用鼠标左键拖动对象(发生这种情况时,也将禁用orbitControls。此部分工作正常)。当未按下“ m”时,它们应返回不可拖动状态,并再次启用orbitControls。

实际:以上所有情况都发生了,但是在按下“ m”后,对象仍然可以拖动。显然,已启用了orbitControls,这使屏幕上出现的所有杂乱无章的事件都发生了。

2 个答案:

答案 0 :(得分:1)

未经测试,但是您应该尝试在onDocumentKeyUp的末尾调用movePoi函数。乍一看似乎仅在单击鼠标左键时才进行是否按下“ m”的验证,而在未按下“ m”键时才进行验证。希望有帮助。

答案 1 :(得分:0)

因此解决方案如下:

  init() {
  
        this.controlsDrag  = new DragControls(this.spheres, this.camera, this.renderer.domElement);
      this.controlsDrag.deactivate();
      
  // EVENT LISTENERS:
  
      map.addEventListener('mousedown', this.startMovePoi, false);
      this.controlsDrag.addEventListener('mouseup', this.stopMovePoi,false);
},

//POI movement around the scene:
    startMovePoi () {
      let controls = this.controls;
      this.controlsDrag.activate();
      this.controlsDrag.addEventListener('dragstart', function () {
        controls.enabled = false;
      });
      this.controlsDrag.addEventListener('dragend', function () {
        controls.enabled = true;
      });
    },
    
    
    stopMovePoi(){
      this.controlsDrag.deactivate();
    }

之前需要一些代码重构。