I am attempting to reassign a child element (entity) to another parent while preserving its position, rotation, and possibly size in the scene. Ideally, I would like to implement a component (let's call it "reparent") that can be added to an entity to "move" it to a specified parent while maintaining its appearance in the scene. For example, in the following HTML code, the green entity should become a child of the red one without altering its position and rotation:
<a-scene id="scene" background="color: grey">
<a-entity id="red"
position="-1 3.5 -4" rotation="30 0 0" material="color: red"
geometry="primitive: cylinder"></a-entity>
<a-entity id="green" reparent="parent: #red"
position="-3 2 -4" rotation="0 45 0" material="color: green"
geometry="primitive: box"></a-entity>
</a-scene>
While this functionality seems achievable using attach at the Three.js level, my attempts to create a simple AFrame component for it have been unsuccessful. It seems that the reparenting done in HTML through AFrame is causing issues.
To illustrate the problem, I have created a test component:
AFRAME.registerComponent('reparent', {
schema: {
parent: {type: 'selector', default: null},
},
init: function () {
const el = this.el;
const parent = this.data.parent;
move = function(evt) {
parent.object3D.attach(el.object3D);
console.log(el.object3D.parent.el.id, el.parentElement.id);
// parent.appendChild(el);
// console.log(el.object3D.parent.el.id, el.parentElement.id);
};
el.sceneEl.addEventListener('loaded', move);
}
});
Upon execution, the result is red scene
: the object3D's parent has changed, but the element's parent remains the scene in HTML. The green box appears as intended at the specified coordinates with the correct rotation.
If I uncomment the two lines of code, a second line red red
is displayed, but the green box disappears. This means that although the element is successfully reparented in HTML, its object3D properties are somehow affected.
Any insights on why this approach fails or any alternative ideas for implementing such a component?
All testing has been performed on AFrame version 1.1.0.