Copy position and rotation from one object to another (Physics)

I used this code for mentioned task, from the title:

sphere.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(sphere.position.x, sphere.position.y, sphere.position.z);

    sphere2.rotationQuaternion = sphere.rotationQuaternion.clone();

    sphere2.position = sphere.position;

For a moment, I was persuaded that I was copying both properties perfectly, it means movement and rotation also. However, the rotation is only partially copied. In many cases, the sphere2 is without rotation, even when the original object is still rotating. Where is the trick?

Adding @PolygonalSun to see if he can help on this one.

1 Like

Hey @Johny_Mickey,

With this line:

sphere2.rotationQuaternion = sphere.rotationQuaternion.clone();

This should be creating a new rotation quaternion using the original sphere’s rotation quaternion values (x,y,z,w), so at the time of assignment, sphere and sphere2 will have the same values but not the same rotation quaternion object. Unless this sphere2.rotationQuaternion is updated each render loop, this value won’t change as sphere.rotationQuaternion changes.

sphere2.position = sphere.position;

For this line, sphere2.position is being set to be the same vector as sphere.position so any changes to sphere.position will affect sphere2 because they’re using the same position vector.

If you want to have sphere2 have copied values from sphere’s position and rotation values, I’d recommend cloning both sphere.rotationQuaternion and sphere.position and then updating their values to match in the render loop (ie. adding a function to scene.onBeforeRenderObservable).

sphere2.rotationQuaternion = sphere.rotationQuaternion.clone();
sphere2.position = sphere.position.clone();
...
scene.onBeforeRenderObservable.add(() => {
     // Move and rotate both spheres separately
});

If you want them to occupy the exact same space and use the exact same rotation (eg. having two character meshes in a game that you can swap between, on the fly), you should have them reference the same rotationQuaternion and position so that you only have to track one.

sphere2.rotationQuaternion = sphere.rotationQuaternion;
sphere2.position = sphere.position;

I’m not sure if this answers your question but if it doesn’t please feel free to let me know and we’ll figure it out.

3 Likes

Hello there, thanks you for your reply. It looks that sourcecode below - is the solution of my problem.
sphere2.rotationQuaternion = sphere.rotationQuaternion;
sphere2.position = sphere.position;

2 Likes