2
votes

Im trying to rotate an object around another object while maintaining its own rotation. I have each objects rotation done im just not sure how to rotate an object around another object. For example I have an array called Planets[Sun,Mercury]. I want the sun to be stationary and allow mercury to rotate around the sun on one axis.

Currently I have the sun and mercury rotating by themselves this is done by: First changing degress to radians.

function degToRad(degrees) 
    {
        return degrees * Math.PI / 180;
    }

Then in my drawScene() I rotate the matrix:

mat4.rotate(mvMatrix, degToRad(rCube), [0, 1, 0]);

and then lastly when I animate the scene I move the object using:

var lastTime = 0;

    function animate() {
        var timeNow = new Date().getTime();
        if (lastTime != 0) 
        {
            var elapsed = timeNow - lastTime;
            rCube -= (75 * elapsed) / 1000.0;
        }

        lastTime = timeNow;
    }

Is there anyway I can pass an origin point into

 mat4.rotate(mvMatrix, degToRad(rCube), [0, 1, 0]);

to make it like:

mat4.rotate(mvMatrix, ObjectToRotateAround, degToRad(rCube), [0, 1, 0]);

I feel as if im not explaining the code I have well. If you wish to have a look it can be found here: https://copy.com/iIXsTtziJaJztzbe

1

1 Answers

0
votes

I think you need to do a sequence of matrix operations and the order of matrix operation matters.

What you probably want in this case is to first translate Mercury to position of Sun, then do the rotation, then reverse the first translation. I have not yet implemented hierarchical objects myself so I dont want to confuse you. But here is the code for my implementation of orbit camera which the yaw function rotates the camera around a target point and you may find it useful:

 yaw: function(radian){
        this.q = quat.axisAngle(this.q, this.GLOBALUP, radian);
        vec3.rotateByQuat(this.dir, this.dir, this.q);
        vec3.cross(this.side,this.GLOBALUP,this.dir);
        vec3.normalize(this.side,this.side);

        this.pos[0] = this.target[0] - this.dir[0] * this.dist;
        this.pos[1] = this.target[1] - this.dir[1] * this.dist;
        this.pos[2] = this.target[2] - this.dir[2] * this.dist;
}

Where this.dir is a normalized vector that always gives the direction from Camera to target and this.dist is the distance between camera and target. You can use matrix rotation instead of quaternion rotation.

Edit: just to add the direction can be calculated by taking the difference in position of the two objects then normalize it.