Namratha
Namratha

Reputation: 11

How do I change the position of an object in A-Frame using setAttribute?

I am facing this issue in 0.8.0. My

<a-sphere id="ball" position="-1 0.59 -4"></a-sphere>

already exists in the <a-scene> of <body>. On click of this ball, I want its position to change to, say -3 0.59 -3. I have tried

document.getElementById("ball").setAttribute('position', '-3 0.59 -3')
document.getElementById("ball").setAttribute('position', {x:-3, y:0.59, z:-3}) 
document.getElementById("ball").object3D.position.set('-3 0.59 -3')

but none of them seem to work.

I am building an app where the position of the ball changes to the point where the cursor is clicked.

Upvotes: 1

Views: 4032

Answers (1)

Piotr Adam Milewski
Piotr Adam Milewski

Reputation: 14655

Both methods:

document.getElementById("ball").setAttribute('position', '-3 0.59 -3')
document.getElementById("ball").setAttribute('position', {x:-3, y:0.59, z:-3})

are correct and move the ball to the selected position. Check it out in my fiddle.


It's possible, that You:
1. Call the methods before the scene is loaded, therefore the ball can't be grabbed.
2. Didn't set up the cursor or the mouse to be working with the rendered objects.
Setting up the mouse is easy - just add the cursor component to the scene:

<a-scene cursor="rayOrigin: mouse">

Be sure to check out the docs on the cursor.

3. Didn't properly set up the event listeners for the click, which I've done like this:

 AFRAME.registerComponent("foo", {
   init: function() {
      this.el.addEventListener("click", (e)=>{
        //do Your thing here
      })
   }
 })

If you're unfamiliar with the component system, make sure to check them out.

Upvotes: 2

Related Questions