I've read the answer to the Three JS Pivot point question and it works okay. But what I'm trying to accomplish involves also the object to rotate based on the pivot rotation.
Let's say for instance that I have an object red
that acts as a pivot for the little object blue
. As soon as the red
object moves or rotates, the blue
object will move and rotate accordingly but keeping the distance between red
and blue
.
For simplicity in the following image we're only in the situation in which the red
object rotates only.
The signature of the function answered in the other question is the following:
function rotateAboutPoint(obj, point, axis, theta, pointIsWorld)
I don't understand how do I get the axis and theta values starting from the red
object rotation.
Or if that function doesn't fit this case, I'm open for other solutions.
I know that if I add the blue
object as a child of the red
one everything will fall in place, but I need the two objects (red
and blue
) to be independent from each other.
To complicate things more I'm not rotating the red
object directly, but I'm using ammo.js
to apply force and torque on it as a dynamic body, but I guess that I can still know its rotation by using red.rotation
UPDATE: I think I've found half solution...
UPDATE 2: My previous update was leading to the wrong direction so I removed it.
This is what I've accomplished so far: I've started learning about quaternions and about getting axis and angle from them.
three.js
makes use of them so I found out this other topic on Stackoverflow on how to get axis and angle representation of a quaternion . Please consider that I'm using the same funcion used in that topic that I've renamed in Maths.getAxisAngleFromQuaternion
.
Here is my code, still not completely working though:
const geo1 = new THREE.BoxGeometry(0.5, 0.2, 0.2);
const geo2 = new THREE.SphereGeometry(0.2, 10, 10);
const mat1 = new THREE.MeshPhongMaterial({ color: 0xff0000 });
const mat2 = new THREE.MeshPhongMaterial({ color: 0x0000ff });
const red = new THREE.Mesh(geo1, mat1);
const blue = new THREE.Mesh(geo1, mat2);
let oldAxisAngle = Maths.getAxisAngleFromQuaternion(red.quaternion);
blue.position.set(1, 0, 0);
scene.add(red, blue);
// loops updates
function loop() {
scene.camera.updateProjectionMatrix();
scene.renderer.render(scene, scene.camera as PerspectiveCamera);
scene.orbitals.update();
scene.world.update(clock.getDelta());
const axisAngle = Maths.getAxisAngleFromQuaternion(red.quaternion);
const theta = axisAngle.angle - oldAxisAngle.angle;
Maths.rotateAboutPoint(blue, red.position, axisAngle.axis, theta);
oldAxisAngle = axisAngle;
red.rotation.y += 0.01;
red.rotation.z += 0.01;
requestAnimationFrame(loop);
}
With the code above, if I rotate only y
or only z
, the blue object rotates as expected, but as soon as I combine those two rotations (y
and z
) the blue object diverges after few instants.
Can someone please explain why that happens and how to fix it? Thanks