在用户编写的 A-Frame 组件中使用实体的材料定义

问题描述 投票:0回答:1

我已经写了一个A-Frame组件(为了这个问题的目的而简化)。

我希望我的组件能够从拥有实体接收

material
信息。

<!DOCTYPE html>
<html>
<head>
    <title>Component Test</title>
    <script src="https://aframe.io/releases/1.4.1/aframe.min.js"></script>
    <script>
        AFRAME.registerComponent('square', {
            schema: {
                size: { type: 'number' }
            },
            init: function () {

                const sizeOffset = this.data.size / 2;
                const points = [];
                points.push(new THREE.Vector2(-sizeOffset, -sizeOffset));
                points.push(new THREE.Vector2(sizeOffset, -sizeOffset));
                points.push(new THREE.Vector2(sizeOffset, sizeOffset));
                points.push(new THREE.Vector2(-sizeOffset, sizeOffset));
                var shape = new THREE.Shape(points);
                var geometry = new THREE.ShapeGeometry(shape);

                //var material = *** How do I get/inherit the component's material (to pass in to the Mesh method below)

                var mesh = new THREE.Mesh(geometry);
                this.el.object3D.add(mesh);
            },
        });

    </script>
</head>

<body>
    <a-scene>
        <a-sky color="#606060"></a-sky>
        <a-entity material="color: purple;" position="-0.5 1.6 -2" geometry="primitive: box; width: 0.2; height: 0.2;"></a-entity>
        <a-entity material="color: green;" position="0.5 1.6 -2" square="size: 0.3;"></a-entity>
    </a-scene>
</body>
</html>

但是当我运行这段代码时,它显示

square
为白色,而不是材料定义中指定的绿色。然而,
geometry
box
确实尊重材料定义(左边紫色)。

我知道我可以为我的组件创建一个接收颜色的参数,但我想保持组件的通用性,并且还能够更改材料的其他属性,而不必将每个属性都添加到我的组件中。

three.js aframe
1个回答
0
投票

由于

material
组件将材质分配给由
THREE.Object
 获取的 
.getObject3D("mesh");
,您可以简单地将网格设置为默认 mesh
setObject3D("mesh", mesh_object);

<script src="https://aframe.io/releases/1.4.1/aframe.min.js"></script>
<script>
  AFRAME.registerComponent('square', {
    schema: {
      size: { type: 'number' }
    },
    init: function() {
      const sizeOffset = this.data.size / 2;
      const points = [];
      points.push(new THREE.Vector2(-sizeOffset, -sizeOffset));
      points.push(new THREE.Vector2(sizeOffset, -sizeOffset));
      points.push(new THREE.Vector2(sizeOffset, sizeOffset));
      points.push(new THREE.Vector2(-sizeOffset, sizeOffset));
      var shape = new THREE.Shape(points);
      var geometry = new THREE.ShapeGeometry(shape);

      var mesh = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
      this.el.setObject3D("mesh", mesh); // set the mesh as the default "mesh" object
    },
  });
</script>

<a-scene>
  <a-sky color="#606060"></a-sky>
  <a-entity material="color: purple;" position="-0.5 1.6 -2" geometry="primitive: box; width: 0.2; height: 0.2;"></a-entity>
  <a-entity material="color: green;" position="0.5 1.6 -2" square="size: 0.3;"></a-entity>
</a-scene>

© www.soinside.com 2019 - 2024. All rights reserved.