我正在尝试根据给定位置通过实体添加一些对象。问题是 setAttribute 不起作用,因为当我调用 getAttribute 时,它返回“未定义”。甚至几何和材料..顺便说一句,我用 html 标签硬编码了一个实体,它工作正常。 我以为我必须等待场景完全加载,但它也不起作用。 谁能告诉我有什么问题吗?我想我错过了一些东西,但我不知道它是什么。
<script>
console.log("0");
AFRAME.registerComponent('gps-coins', {
init: function () {
console.log("started1");
for (var i = 0; i < 5; i++) {
var coinEntity = document.createElement('a-entity');
coinEntity.setAttribute('geometry', 'primitive: cylinder; radius: 5; height: 1'); // Adjust size
coinEntity.setAttribute('material', 'color:green'); // Coin color
coinEntity.setAttribute('rotation', '0 90 90');
coinEntity.setAttribute('position', '5 5 5');
console.log(coinEntity.getAttribute('geometry'));
console.log(coinEntity.getAttribute('material'));
// Append the coin to the scene
this.el.appendChild(coinEntity);
}
}
});
console.log("very end");
</script>
我想在场景中创建 10 个硬币,并为其设置一些属性,但是当我调用 getAttribute 时,我得到了未定义的信息。
您为几何体和材质设置的属性看起来不错,但如果您编码正确,则您没有将它们正确设置为 coinEntity ? 此外,您还将所有硬币的位置设置为相同的坐标(5,5,5)。这意味着它们将在同一位置重叠。您可能需要调整每个硬币的位置,以便它们分布在场景中。
那么你可以试试这个吗?
<script>
AFRAME.registerComponent('gps-coins', {
init: function () {
for (var i = 0; i < 5; i++) {
var coinEntity = document.createElement('a-entity');
coinEntity.setAttribute('geometry', {
primitive: 'cylinder',
radius: 0.5,
height: 0.1
});
coinEntity.setAttribute('material', 'color: green');
coinEntity.setAttribute('rotation', '0 0 0');
// Adjust position for each coin
var posX = Math.random() * 10 - 5; // Random position between -5 and 5
var posY = Math.random() * 10 - 5;
var posZ = Math.random() * 10 - 5;
coinEntity.setAttribute('position', {
x: posX,
y: posY,
z: posZ
});
this.el.appendChild(coinEntity);
}
}
});
</script>