【发布时间】:2019-05-06 08:23:14
【问题描述】:
如何将对象的长度转换为 X 坐标?我有一个动态增长的盒子,里面有许多从左到右排列的球体。我想把盒子放在屏幕的中间,所以它的中心在屏幕的中心。当我在页面上创建盒子元素时,它的轴心在左上角,但我不知道如何说“将它放在中心减去盒子宽度的一半”。
这是创建盒子的代码:
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” 在 $.setFromObject (three.js:7891) 在 $n.update (three.js:41123) 在 c。 (tvr2.html:103) 在 TWEEN.Tween.update (tween.js:399)
我应该指出,如果我在创建/更新该助手后记录它,它没有“盒子”属性或几何形状。
【问题讨论】:
-
在计算边界框之前等待实体先加载?
addEventListener('object3dset', function (evt) { if (evt.detail.name === 'mesh') { ... })
标签: javascript 3d three.js aframe