2017-08-16 48 views
0

我想调整只有一个对象的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} 

回答

1

你既可以:

  • 设置临时position变量,只改变所需的部分:使用Object.Assign()削减临时工的
    let pos = this.el.getAttribute('position'); pos.x += velocity; this.el.setAttribute('position',pos);
  • 使用赖Witmann的想法: 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();
    这很有趣,但我认为这是一个可怕的想法,当创建一个商业/ proffesional项目,因为每个框架将会是。

  • 使用threejs object3D属性:
    this.el.object3D.position.x += velocity;
    检查它在我的小提琴:https://jsfiddle.net/gftruj/dqyszzz5/1/
    请注意,以后您将不能打电话getAttribute(),因为位置分量不改变。

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

+0

不会改变底层Three.js位置后来弄乱了什么吗?如果我在箱子上做'getAttribute('position')',它不是旧的位置吗? 而第二种解决方案是我目前正在做的,看起来可能是唯一的方法。 – boxtrain

+0

@jbjw yup,正如我写的,我通常使用'临时变量'选项来保持位置,我已经更新了我的anwser以避免混淆,如果你正在寻找一个干净的班轮,使用Rainers的想法,我仍然希望将参考中的位置对象作为一个整体。 –

1

你也可以使用Object.assign。这样的事情:

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

这仍然覆盖整个位置,但看起来这是唯一的方法和'对象。assign'比我的分解 - 重构解决方案要漂亮得多。谢谢! – boxtrain