Half_Duplex
Half_Duplex

Reputation: 5234

OpenGL matrix transformation for a revolution

I wrote the following code to rotate a cube on x axis an entire revolution, then the y axis, and back and forth. The code generates the desired result.

- (void)update
{
if (_x_axis) {
    if (i >= 6.28) {
        i = 0;
        _x_axis = false;
    } else {
        float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
        GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f);
        self.effect.transform.projectionMatrix = projectionMatrix;
        GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -3.0f);
        modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, i, 0.0f, 1.0f, 0.0f);
        self.effect.transform.modelviewMatrix = modelViewMatrix;
        i += .01;
    }
} else {
    if (i >= 6.28) {
        i = 0;
        _x_axis = true;
    } else {
        float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
        GLKMatrix4 projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(65.0f), aspect, 0.1f, 100.0f);
        self.effect.transform.projectionMatrix = projectionMatrix;
        GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -3.0f);
        modelViewMatrix = GLKMatrix4Rotate(modelViewMatrix, i, 1.0f, 0.0f, 0.0f);
        self.effect.transform.modelviewMatrix = modelViewMatrix;
        i += .01;
    }
}

My question is, when I change the increment to i to something such as .02 or .2 or .3, why does the cube still rotate exactly one revolution?

If i is incremented by .2, the last value of i used in the transformation would be 6.2 before it would be reset and the rotation axis was changed. Basically, what is keeping the cube level? I would think with the larger increment of i, the cube wouldn't make an entire revolution before switching axis.

Upvotes: 0

Views: 506

Answers (1)

Stefan Hanke
Stefan Hanke

Reputation: 3518

6.28 = 2*M_PI, with the code given a full rotation. The parameter i is straight given to GLKMatrix4Rotate. If you want different lengths, you can vary this constants in the conditions, or map the parameter i before calling GLKMatrix4Rotate.

For the the second approach, modify the code:

  1. Change the interval of i to [0;1], and make the step width a bit smaller.
  2. Call GLKMatrix4Rotate with i*2*M_PI.

Now the animtion generally runs as previous, however, you can twist this with easing functions.

Upvotes: 1

Related Questions