如何设置对象的某些坐标而不重置其他坐标?

How do I set some of an object's coordinates without resetting the other ones?

我试图只调整对象的 Y 坐标,同时保持 X 和 Z 坐标不变。我使用的唯一方法是获取对象的位置并组成一个新的部分修改的位置。它不漂亮,而且似乎效率低下。看起来这可能是因为 position is a single-property component,所以这可能是不可能的。

这是我目前的解决方案:

https://glitch.com/edit/#!/aframe-position-example

index.html:

<html>
  <head>
    <script src="https://aframe.io/releases/0.6.0/aframe.min.js"></script>
  </head>
  <body>
    <a-scene>
      <a-camera id="camera"></a-camera>
    </a-scene>
    <script src="index.js"></script>
  </body>
</html>

index.js:

const camera = document.querySelector( '#camera' )

console.log( camera.getAttribute( 'position' ) )
// {x: 0, y: 1.6, z: 0}

// overwrites original position, as expected
camera.setAttribute( 'position', { x: 0, y: 0, z: 5 } )
console.log( camera.getAttribute( 'position' ) )
// {x: 0, y: 0, z: 5}

// overwrites original position (including z, defaults to 0), maybe not expected
camera.setAttribute( 'position', { x: 5, y: 5 } )
console.log( camera.getAttribute( 'position' ) )
// {x: 5, y: 5, z: 0}

// overwrites original position (x and z become 0), maybe not expected
camera.setAttribute( 'position', 'y', 10 )
console.log( camera.getAttribute( 'position' ) )
// {x: 0, y: 10, z: 0}

// how to change some position variables and keep the other ones the same
let oldPos = camera.getAttribute('position')
let newPos = { x: 4, y: oldPos.y, z: oldPos.z }
camera.setAttribute( 'position', newPos )
console.log( camera.getAttribute( 'position' ) )
// {x: 4, y: 10, z: 0}

您可以:

  • 设置一个临时position变量,只改变需要的部分:
    let pos = this.el.getAttribute('position'); pos.x += velocity; this.el.setAttribute('position',pos);
  • 使用 Rainer Witmann 的想法,通过使用 Object.Assign() 切割临时物: this.el.setAttribute('position', Object.assign({}, this.el.getAttribute('position'), {x: newX}));
    看起来更短,但我喜欢将整个位置作为临时变量: 住在这里:https://jsfiddle.net/gftruj/dqyszzz5/4/

  • 直接修改position组件,修改数据,调用update()函数:
    this.el.components.position.data.z-=2; this.el.components.position.update();
    这很有趣,但我认为在创建 commercial/proffesional 项目时这是一个糟糕的主意,因为每个框架集成都会如此。

  • 使用 threejs object3D 属性:
    this.el.object3D.position.x += velocity;
    在我的 fiddle 中查看:https://jsfiddle.net/gftruj/dqyszzz5/1/
    请注意,稍后您将无法调用 getAttribute(),因为位置组件不会更改。

在你的故障中你使用了第一个选项,但是你不需要单独使用位置对象属性:setAttribute('position',{x:pos.x,y:pos.y,z:pos.Z});,你可以简单地使用整个对象:setAttribute('position',pos);

您也可以使用 Object.assign。像这样:

camera.setAttribute('position', Object.assign({}, camera.getAttribute('position'), {x: 5})