[SOLVED] Trying to rotate a sphere from any angle so that it's child can reach a specific position

Hello! I’m new here and I’ve been using Three.js for the past 2 weeks…

I’ve been trying to do this thing for days and now I really need help.
My goal is to rotate the sphere from its current angle so that it’s child object reaches a specific destination position(in this case: X=0, Y=1, Z=?). I have a ‘go()’ function that triggers the action and It works as expected when the sphere’s rotation is set(0, 0, 0) but if I apply some arbitrary rotation to the sphere then run the function, it presents some unexpected rotations. Also if the child object is at the destination position after an initial calling of the ‘go()’ function, when I re-run the function it rotates the sphere - which shouldn’t happen because the child object is already at the destination. I tried to mitigate this by using ‘toFixed(1)’ to round off the additional values after the decimal point for X, Y and Z coordinates to 0 so that it doesn’t produce a rotation angle after calculation as you will see in the code; though I don’t like this method.

Here is the code to the fiddle
You can change the location of the child object(blue cube) by setting it’s GPS coordinate(line: 50) in the ‘init’ function and you may set an arbitrary rotation on the sphere(line: 125). The ‘go’ function is set to run automatically because for some reason whenever I invoke it from the console the fiddle updates. :man_shrugging:t4:

This solved it for me.

let startQuaternion;
let endQuaternion;

let getQuaternionFromVectors = (vecFrom, vecTo) => {
    return new THREE.Quaternion().setFromUnitVectors(vecFrom, vecTo);
}

function go(){
    startQuaternion = sphere.quaternion.normalize();
    endQuaternion = getQuaternionFromVectors( aMesh.position.normalize(), destination.normalize() );

    let inBetween = startQuaternion.slerp( endQuaternion, 1 );
    sphere.setRotationFromQuaternion(inBetween);
}
1 Like