2017-03-05 62 views
0

我会如何将对象的长度转换为X坐标?我有一个可以动态增长的框,其内部的许多球体从左至右排列。我想把盒子放在屏幕的中间,所以它的中心位于屏幕的中心。当我在页面上创建框元素时,它的枢轴位于左上角,但我无法解决如何说“放在中间减去框的一半宽度”。根据宽度的A帧位置对象

这里是创建代码盒子:

for (var i=1; i<=hudItems.length; i++) { 
      var newSphere = document.createElement('a-sphere'); 
      newSphere.setAttribute('radius', .3); 
      newSphere.setAttribute('color', '#ECECEC'); 
      newSphere.setAttribute('position', hudEl.object3D.position.x+offSet*i + ' 0 0'); 
      newSphere.setAttribute('src', hudItems[i-1].thumb); 
      newSphere.setAttribute('translate', "0 0.6 0"); 

      var sphereShadow = document.createElement('a-image'); 
      sphereShadow.setAttribute('src', 'radial-shadow-3.png'); 
      sphereShadow.setAttribute('rotation', '-90 0 0'); 
      sphereShadow.setAttribute('scale', '1 1 1'); 
      newSphere.appendChild(sphereShadow); 
      hudEl.appendChild(newSphere); 
     } 
     sceneEl.appendChild(hudEl); 

希望任何指针 - 有可能是一个简单俗称的方法来做到这一点,我只是不知道的还

**更新:

使用BoundingBoxHelper尝试 - 我以前就是这样创建hud:

<a-entity id="hud" position="-1.2 -2.39 -7" pivot="0 0 0" ></a-entity> 

而且我甚至试过这个,所以我可以看到它:

<a-entity id="hud" geometry="primitive: box; width:2; height:2;  depth:2" position="0 0 -7" pivot="0 0 0" ></a-entity> 

我加入这个代码:

var hud = document.querySelector('#hud').object3D; 
var helper = new THREE.BoundingBoxHelper(hud, 0xff0000); 
helper.update(); 
    var min = helper.box.min; 
    var max = helper.box.max; 
    var newX = -1 * (max.x - min.x)/2; 
    hudEl.setAttribute('position', newX + ' 0 0') 

但我得到这个错误: 遗漏的类型错误:无法读取属性'updateMatrixWorld'undefined at $ .setFromObject(three.js:7891) at $ n.update(three.js:41123) 在c。 (tvr2.html:103) at TWEEN.Tween.update(tween.js:399)

我应该指出,如果我在创建/更新它之后记录该帮助器,它没有“box”属性,或者几何。

+0

等待实体在计算边界框之前先加载? 'addEventListener('object3dset',function(evt){if(evt.detail.name ==='mesh'){...})' – ngokevin

回答

0

您可能希望首先获取对象的边界框,包括其任何子对象的边界框。 THREE.BoxHelper可以这样做:

var object = el.object3D; 
var helper = new THREE.BoundingBoxHelper(object); 
helper.update(); 

然后,居中对齐X轴对象:当你添加旋转

var min = helper.box.min; 
var max = helper.box.bax; 
el.setAttribute('position', { 
    x: -1 * (max.x - min.x)/2, 
    y: 0, 
    z: 0 
}); 

数学变得更为复杂,但是这是一般的方法。

+0

尝试了一些变化,但似乎我的实体没有边界框,更新了我上面的问题 –

相关问题