EARTH 801
Computation and Visualization in the Earth Sciences

Lesson 6: Interactive 3D Rotation

PrintPrint

Now let’s modify our rotating square so that we are controlling the rotation with the mouse. You know all the commands to make this work already. Here’s how it is done. Decide how much of a rotation you want to allow (a full rotation is 360 degrees, or 2*PI radians). Then map this angle to the width or height of the screen based on the mouse location.

Example 6.3

Here is an example of rotation about the Y axis based on the X location of the mouse. Does this seem counterintuitive? Think about it for a minute. Rotation around Y basically means side-to-side rolling, so to me it seems more intuitive to control this motion with the side-to-side, or X, position of the mouse.

//rotating orange square
//rotates around Y axis with mouse

void setup(){
   size(400, 400, P3D);
}

void draw(){
   background(255);
   translate(width/2,height/2,0);
   float rotAngle = 2*PI*mouseX/width;
   rotateY(rotAngle);
   fill(250, 100, 13);
   strokeWeight(4);
   rectMode(CENTER);
   rect(0, 0, 200, 200);
}
orange square rotates with mouse-over
Our friend the orange square rotates with mouse-over
E. Richardson
cartoon Eliza alerting you that instructions come next

The most important line of this program is the one that says:

float rotAngle = 2*PI*mouseX/width;

That line does a lot for you. It tells Processing that you want one whole rotation to occur over the distance that equals the width of the window and you want the amount of rotation to be dependent on the X position of the mouse. It is a good idea to experiment with putting different numbers into this line to see what they do. For example, try getting rid of the number 2 or changing it to 4 and see what happens. What would you have to change to get one whole rotation about the X axis based on the Y position of the mouse? Here's a screencast of the mouse-controlled rotation program (and a captioned version) so you can see what it looks like when it is running.

Quiz Yourself!