CHAPTER 3: Building a 3D World (^69)
Any OpenGL call must have a current context to work, so it needs to be set ahead of
everything else, hence the extra line ahead of setClipping(). If it works right, you should
see something that looks exactly like the original bouncy cube! Wait, you’re not
impressed? OK, let’s add some rotations to the thing.
Taking ’er Out for a Spin
Now it’s time to add some more interesting animation to the scene. We’re going to be
spinning this slowly besides bouncing it up and down. To the top of drawInRect(), add
the following:
static GLfloat spinX=0;
static GLfloat spinY=0;
Next add the following lines to the bottom of drawInRect ():
spinY+=.25;
spinX+=.25;
And right before the glTranslatef() call, add the following:
glRotatef(spinY, 0.0, 1.0, 0.0);
glRotatef(spinX, 1.0, 0.0, 0.0);
Now run again. ‘‘Hey! Huh?’’ will be the mostly likely response. The cube doesn’t seem
to be spinning, but instead it’s rotating around your viewpoint (while bouncing at the
same time), as shown in Figure 3-8. This illustrates one of the most confusing elements
in basic 3D animation: getting the order of the translations and rotations correct.
(Remember the discussion in Chapter 2?)
Consider our cube. If you want to have a cube spinning in front of your face, which
would be the proper order? Rotate and then translate? Or translate and then rotate?
Reaching way back to fifth-grade math, you might remember learning something about
addition and multiplication being commutative. That is, the order of operations was not
critical: a+b=b+a, or ab=ba. Well, 3D transformations are not commutative (finally, a
use for something I’d never thought I’d use!). That is, rotationtranslation is not the same
as translationrotation. See Figure 3-9.
The right side is what you are seeing right now in the rotating cube example. The cube is
being translated first and then rotated, but because the rotation takes place around the
‘‘world’’ origin (the viewpoint’s location), you see it as if it’s spinning around your head.
Now to the obvious does-not-compute moment: are the rotations not placed before the
translations in the example code anyway?
singke
(singke)
#1