Search code examples
javascriptanimationaframe

I want to define a variable for the attribute of aframe animation


I wrote the code below

Finally, when set touchPoint to to, it doesn't work.

// getModel
const model = document.getElementById('model') 
// getPlaceGround
const ground = document.getElementById('ground')
// click ground
ground.addEventListener('click', (event) => {
  console.log('clicked ground')
  // get touch position
  const touchPoint = event.detail.intersection.point
  console.log(touchPoint) // touchPoint
  console.log(touchPoint.x) // touchPoint.x
  console.log(touchPoint.y) // touchPoint.y
  console.log(touchPoint.z) //// touchPoint.z
  
 

tried
1:bad
2:bad
3:bad
4:bad
5:good but, I want to set variable
6:good but, I want to add animation

 model.setAttribute('animation', 'property: position; to: touchPoint')
 model.setAttribute('animation', 'property: position; to: touchPoint.x touchPoint.y touchPoint.z ')
 model.setAttribute('animation', `property: position; to: ${touchPoint}`)
 model.setAttribute(`'animation', 'property: position; to: ${touchPoint}'`)
 model.setAttribute('animation', 'property: position; to: -4 -4 2')
 model.setAttribute('position', touchPoint)

Solution

  • Here is a working jsFiddle But first, lets talk about your tries:

    1. Just a string not a variable
    model.setAttribute('animation', 'property: position; to: touchPoint')
    // to = tochPoint <--- hardcoded string not a variable
    
    model.setAttribute('animation', 'property: position; to: touchPoint.x touchPoint.y touchPoint.z ')
    // to = touchPoint.x touchPoint.y touchPoint.z <--- hardcoded string not a variable
    

    You just added touchPoint as a hardcoded string and not as a variable

    1. Huge object
    model.setAttribute('animation', `property: position; to: ${touchPoint}`)
    // to = {.....} <--- object but expected a string 
    
    model.setAttribute(`'animation', 'property: position; to: ${touchPoint}'`)
    // to = {.....} <--- object but expected a string 
    

    touchPoint is an object contains a lot of other stuff but your "to" property is expecting a string.

    The Solution:

    model.setAttribute('animation', `property: position; to: ${touchPoint.x} ${touchPoint.y} ${touchPoint.z}`)
    
    // to = -4 -4 -2
    

    Hope I could help you if you have any questions feel free to contact me