2017-08-16 50 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