我如何获取相机的当前位置?这样我就可以旋转我的天空实体。
假设我有:
<a-scene>
<a-camera id="camera></a-camera>
<a-sky id="mySky"></a-sky>
</a-scene>
我如何获取相机的当前位置?这样我就可以旋转我的天空实体。
假设我有:
<a-scene>
<a-camera id="camera></a-camera>
<a-sky id="mySky"></a-sky>
</a-scene>
获取相机的位置:
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.
}
});
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>
getAttribute('position')
? - ngokevin