Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Scene: Object3D.attach keeps world position when matrixAutoUpdate is false (#208, supersedes #105)

Evan (Yifeng) Wang2c9a2ff3b60a
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index c010c1a..1b8c4a2 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -725,6 +725,8 @@ export class Object3D {
const m = new Matrix4().copy(this.matrixWorld).invert().multiply(object.matrixWorld);
object.parent?.remove(object);
m.decompose(object.position, object.quaternion, object.scale);
+ // With automatic updates off, keep the explicit matrix in sync with the new local transform.
+ if (!object.matrixAutoUpdate) object.matrix.copy(m);
this.add(object);
object.updateWorldMatrix(false, true);
return this;
diff --git a/packages/scene/test/three-compat.test.ts b/packages/scene/test/three-compat.test.ts
index 4660398..1232760 100644
--- a/packages/scene/test/three-compat.test.ts
+++ b/packages/scene/test/three-compat.test.ts
@@ -201,6 +201,25 @@ test("Mesh.copy and clone: material arrays are independent, but geometry and mat
assert.equal(single.clone().material, red, "a single material remains shared");
});
+test("Object3D.attach preserves world position with matrixAutoUpdate disabled, as three.js r187", () => {
+ const source = new THREE.Group();
+ source.position.set(5, 0, 0);
+ const target = new THREE.Group();
+ target.position.set(-2, 0, 0);
+ const child = new THREE.Object3D();
+ child.position.set(3, 0, 0);
+ child.updateMatrix();
+ child.matrixAutoUpdate = false;
+ source.add(child);
+
+ assert.deepEqual(child.getWorldPosition(new THREE.Vector3()).toArray(), [8, 0, 0], "source world x: 5 + 3");
+ assert.equal(target.attach(child), target);
+ assert.equal(child.parent, target);
+ assert.deepEqual(child.position.toArray(), [10, 0, 0], "new local x: 8 - (-2)");
+ assert.deepEqual(child.getWorldPosition(new THREE.Vector3()).toArray(), [8, 0, 0], "world position must stay fixed");
+ assert.equal(child.matrix.elements[12], 10, "explicit matrix must use the new local translation");
+});
+
test("Raycaster: the nearest hit first, front faces of single-sided materials, instanceId, near / far", () => {
const scene = new THREE.Scene();
const near = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.MeshStandardMaterial());