Alex Under
Alex Under

Reputation: 1489

Three.js How to point child of Object3d to face camera?

Here is the thing. I have an Object3d that is composed of 6 planes settled to form a cube. Now, after applying quaternion rotation based on mouse input and after the cube has stopped - I need the cube to turn straight to the camera at its closest side (plane child). What I am doing now is I’m getting the current Euler angles of my Object3d matrix, applying rotation to this matrix and setting it back to my object’s quaternion with setFromRotationMatrix() function. Sometimes this method works (usually at low angles) and sometimes the Z axis behaves wrong (or maybe Y, or even all of them, can’t tell).

Now, I certainly could just calculate the closest side and apply direct quaternion of this side to my object, which works, but that gives me no animation.

I’m using this code to get my current angles: http://www.cs.princeton.edu/~gewang/projects/darth/stuff/quat_faq.html#Q37. Based on that I calculate the closest 90 degrees rotation for every axis:

        function lookAtCamDeg(val){
            var d = 1;
            var s = 1;
            var newAngle;

            if(val < 0)d*=-1;

            val = Math.abs(val);

            if(val <= 45)s*=-1;
            if(val > 45)val=90-val;

            newAngle = val*d*s;

            return newAngle;
        }

And applying that to turn my cube:

            var angles = getAngles();http://www.cs.princeton.edu/~gewang/projects/darth/stuff/quat_faq.html#Q37
            var newX = lookAtCamDeg(angles.x);
            var newY = lookAtCamDeg(angles.y);
            var newZ = lookAtCamDeg(angles.z);

            var ma = cube.matrix;
            ma = ma.rotateX(-newX*DEGREES)
            ma = ma.rotateY(-newY*DEGREES)
            ma = ma.rotateZ(-newZ*DEGREES)
            cube.quaternion.setFromRotationMatrix(ma);

What I am thinking now is to try using separate planes of my cube (children) and based on their normals apply lookAt() method, but don’t know how to do it, since I need to rotate the whole object, not just one child. Could someone please lead me to the right direction to go? What is the best way to achieve my needs?

Upvotes: 0

Views: 652

Answers (1)

bjorke
bjorke

Reputation: 3305

The THREE.Quaterion object contains methods for interpolation. So calculate the quaternion value of the original face normal, the quaternion you get here from setFromRotationMatrix(ma), and then apply THREE.Quaterion.slerp() repeatedly to get in-betweens, which can apply to cube.quaternion

Upvotes: 0

Related Questions