首页 > 解决方案 > 我想为aframe动画的属性定义一个变量

问题描述

我写了下面的代码

最后,当将 touchPoint 设置为 to 时,它不起作用。

// 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
  
 

试过
1:bad
2:bad
3:bad
4:bad
5:good 但是,我想设置变量
6:good 但是,我想添加动画

 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)

标签: javascriptanimationaframe

解决方案


这是一个有效的jsFiddle 但首先,让我们谈谈您的尝试:

  1. 只是一个字符串而不是变量
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

您刚刚将 touchPoint 添加为硬编码字符串而不是变量

  1. 巨大的物体
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是一个包含许多其他内容的对象,但您的“to”属性需要一个字符串。

解决方案:

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

// to = -4 -4 -2

希望我能帮助你,如果您有任何问题,请随时与我联系


推荐阅读