【问题标题】:A-frame position object according to widthA框根据宽度定位对象
【发布时间】: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


【解决方案1】:

您可能希望从获取对象的边界框开始,包括它的任何子对象。 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
});

随着您添加旋转,数学变得更加复杂,但这是一般方法。

【讨论】:

  • 尝试了一些变化,但似乎我的实体没有边界框,更新了我上面的问题
【解决方案2】:

这些答案现在都已经过时了。

 this._sidePane.addEventListener('object3dset', e => {
      if(e.detail.type === 'mesh'){
        var size = new window.THREE.Box3().setFromObject(object).getSize()
})

为我工作

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 2017-03-26
    • 2020-08-18
    相关资源
    最近更新 更多