1
votes

I'm using a camera and barcode markers. In order for my cannon to shoot I need to spawn a sphere when a clicked. I tried to get the marker position by using .getAttribute('position') but I'm getting disappointing results e.g. null and [object, object]. Is there a real way to to access the coordinates of a marker in AFrame? So far it creates a sphere but right in the camera because its unable to find the location of the marker.

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
this line is a potential bug: var sceneEl = document.querySelector('a-scene'); When using querySelector, you need to include . if it's a class or # if it's an id. Since you haven't included HTML, I can't tell for sure, but I'd look there first. P.S. If you include more complete code, we'd be able to help you faster/more accurate. Welcome to SO :)nemanja

1 Answers

0
votes

Provided the marker is being recognized and the references are correct

markerEl.getAttribute('position')

should return the current marker position.


If your script is in the <head> element, the marker may not yet exist when the code is executed.

It's a good idea to throw your code into an a-frame component:

HTML:

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

js:

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


working glitch here
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);
   });
  }

When the marker gets out of vision, it's position is 'last remembered'. So it's the same place on the screen. That's why there's a return if the marker element is not visible.

It seems to be working as you want since the ball is falling out of a transparent box on the marker (the box is a nice way to be sure the marker is recognized):

enter image description here