如何在A-Frame中监听相机的世界位置?

12

我如何获取相机的当前位置?这样我就可以旋转我的天空实体。

假设我有:

<a-scene>
  <a-camera id="camera></a-camera>
  <a-sky id="mySky"></a-sky>
</a-scene>
2个回答

23

获取相机的位置:

var pos = document.querySelector('#camera').getAttribute('position');

我们可以通过转换相机的本地位置来获取相机的世界位置:

var cameraEl = document.querySelector('#camera');
var worldPos = new THREE.Vector3();
worldPos.setFromMatrixPosition(cameraEl.object3D.matrixWorld);
console.log(worldPos.x);

要监听变化,请使用componentchanged事件:

cameraEl.addEventListener('componentchanged', function (evt) {
  if (evt.detail.name !== 'position') { return; }
  console.log(evt.detail.newData);
});

更高效的方法可能是轮询:

AFRAME.registerComponent('camera-listener', {
  tick: function () {
    var cameraEl = this.el.sceneEl.camera.el;
    cameraEl.getAttribute('position');
    cameraEl.getAttribute('rotation');

    // Do something.
  }
});

1
非常有用,谢谢。希望A-frame的所有监听器都能作为文档的一部分。 - benbyford
@ngokevin,目前是否可以检索到videosphere的位置? - Syed Faizan
getAttribute('position') - ngokevin

4
基于Kevin Ngo的回答,我定义了一个名为camera-logger的组件,它可以每秒将相机的位置和方向记录到JavaScript控制台中。这个组件可以添加到任何aframe实体中。
<!-- define camera logger component -->
<script>
AFRAME.registerComponent('camera-logger', {

  schema: {
    timestamp: {type: 'int'},
    seconds: {type: 'int'} // default 0
  },

  log : function () {
    var cameraEl = this.el.sceneEl.camera.el;
    var rotation = cameraEl.getAttribute('rotation');
    var worldPos = new THREE.Vector3();
    worldPos.setFromMatrixPosition(cameraEl.object3D.matrixWorld);
    console.log("Time: " + this.data.seconds 
                + "; Camera Position: (" + worldPos.x.toFixed(2) + ", " + worldPos.y.toFixed(2) + ", " + worldPos.z.toFixed(2) 
                + "); Camera Rotation: (" + rotation.x.toFixed(2) + ", " + rotation.y.toFixed(2) + ", " + rotation.z.toFixed(2) + ")");        
  },

  play: function () {
    this.data.timestamp = Date.now();
    this.log();
  },

  tick: function () {  
    if (Date.now() - this.data.timestamp > 1000) {
      this.data.timestamp += 1000;
      this.data.seconds += 1;
      this.log();
    }
  },
});
</script>

...

<!-- add the logger to your camera -->
<a-entity camera camera-logger>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接