How To...

Animate Dancing Arms

atan2 diagram

This example adds a pair of arms to the robot and uses the mouseX and mouseY to rotate() the upper arms and forearms of the robot. It's a bit tricky, because you have to isolate the translate and rotate functions from each other. It's especially important the each component of the robot be based at 0,0 so rotate() can do its job properly.

PROCESSING

Dancing Arms

// Dancing Arms
// v1.0

void setup() {
  size(500, 500);
  ellipseMode(CENTER);
}

void draw() {
  background(128);
  textAlign(CENTER);
  text("MOVE MOUSE VERTICALLY TO ROTATE FOREARMS", width/2, 460);
  text("MOVE MOUSE HORIZONTALLY TO ROTATE UPPER-ARMS", width/2, 475);
  translate(width/2, height/2);
  scale(2);
  drawRobot();
}

void drawRobot() {
  // RIGHT Arm ---------------------------------------------
  strokeWeight(8);
  pushMatrix();             // Position and rotate top arm
    translate(-20, -30);
    rotate(radians(map(mouseX,0,width,15,165)));   
    line(0, 0, 0, 30);      // Top arm
    pushMatrix();           // Position and rotate fore arm
      translate(0, 30);
      rotate(radians(map(mouseY,0,height,5,150)));    
      line(0, 0, 0, 30);    // Fore arm
      strokeWeight(1);
      pushMatrix();         // Position hand
        translate(0, 35);
        rotate(radians(90));
        arc(0, 0, 15, 15, radians(45), radians(320), PIE); // hand
      popMatrix();
    popMatrix();
  popMatrix();
  // LEFT Arm ---------------------------------------------
  strokeWeight(8);
  // Isolate the left arm's matrix
  pushMatrix();             // Position and rotate top arm
    translate(20, -30);
    rotate(radians(map(mouseX,0,width,345,195)));    
    line(0, 0, 0, 30);      // Top arm
    // Isolate the fore-arm's matrix
    pushMatrix();           // Position and rotate fore arm
      translate(0, 30);
      rotate(radians(map(mouseY,0,height,355,210)));    
      line(0, 0, 0, 30);    // Fore-arm
      strokeWeight(1);
      // Isolate the hand's matrix
      pushMatrix();         // Position hand
        translate(0, 35);
        rotate(radians(90));
        arc(0, 0, 15, 15, radians(45), radians(320), PIE);
      popMatrix();
    popMatrix();
  popMatrix();
  // Draw the rest of the robot
  strokeWeight(1);
  ellipse(0, -65, 30, 30);   // Head
  ellipse(-10, -70, 10, 10); // Left Eye
  ellipse(-10, -70, 2, 2);   // Left Iris
  ellipse(10, -70, 10, 10);  // Right Eye
  ellipse(10, -70, 2, 2);    // Right Iris
  fill(255);
  strokeWeight(3);
  line(-10, -60, 10, -60);    // Mouth
  strokeWeight(1);
  rect(-5, -50, 10, 10);      // Neck
  ellipse(0, 20, 40, 40);     // Wheel base
  rect(-20, -40, 40, 60);     // Body
}