如何使用JavaScript在AFrame中查找标记位置?

时间:2018-11-28 17:30:16

标签: javascript jquery aframe

我正在使用相机和条形码标记。为了使我的大炮射击,我需要在单击时生成一个球体。我试图通过使用 .getAttribute('position')来获得标记的位置,但结果却令人失望,例如null和[object,object]。有没有一种真正的方法来访问AFrame中标记的坐标?到目前为止,它创建了一个球体,但是恰好在相机中,因为它无法找到标记的位置。

Javascript

var sceneEl = document.querySelector('a-scene'); //select scene
    var markerEl = document.querySelector('#cannonMarker');
  // trigger event when button is pressed.
  document.addEventListener("click", function (e) {

    var pos = markerEl.getAttribute('position');
    var Sphere = document.createElement('a-sphere');



    Sphere.setAttribute('dynamic-body', {
    shape: 'sphere',
    mass: 4
    });

    Sphere.setAttribute('position', pos);




    sceneEl.appendChild(Sphere);

    console.log('Sphere coordinates:' + pos);



 });

1 个答案:

答案 0 :(得分:0)

提供了可识别的标记并且引用正确

const log = console.log
let string = 'Hello ♥ world! ♥'
let textEncoder = new TextEncoder()
let bytes = textEncoder.encode(string)
let textDecoder = new TextDecoder('utf-8', {fatal: true})
try {
  // Comment away this line and the code below will work
  log(textDecoder.decode(new DataView(bytes.buffer, 0, 19)))
} catch (e) {
  log('After this failed the next try will also fail')
}
log(textDecoder.decode(new DataView(bytes.buffer, 0, 20)))

应返回当前标记位置。


如果脚本位于markerEl.getAttribute('position') 元素中,则在执行代码时标记可能还不存在。

将代码放入a框架组件中是个好主意:

HTML:

<head>

js:

<a-scene ball-spawner></a-scene>


我对您的代码(working glitch here)做了一些修改:

AFRAME.registerComponent('ball-spawner', {
  init: function() {
  // your code here - the scene should be ready
  }
})

当标记消失时,它的位置是“最后被记住”的位置。因此,它在屏幕上的位置相同。这就是如果标记元素不可见的情况下会有var sceneEl = document.querySelector('a-scene'); //select scene var markerEl = document.querySelector('a-marker'); // trigger event when button is pressed. sceneEl.addEventListener("click", function (e) { if (markerEl.object3D.visible === false) { return; } var pos = markerEl.getAttribute('position'); var Sphere = document.createElement('a-sphere'); Sphere.setAttribute('radius', 0.5) Sphere.setAttribute('dynamic-body', { shape: 'sphere', mass: 4 }); Sphere.setAttribute('position', pos); sceneEl.appendChild(Sphere); }); } 的原因。

由于球正从标记上的透明框中掉出(该框是确保可以识别标记的好方法),因此似乎可以按需要工作:

enter image description here

相关问题