Grids, Direction and Rotation

Sign in to queue

Description

See direction and rotation sketch in action

In this lesson, we build on the introduction to Trigonometry we explored previously and add the final piece of the puzzle, working with tangents using the ATAN2() function.  This special function allows us to figure out the direction of rotation between any two elements and we use it to build a fish eye bulging effect that reacts to the pointer as it moves across the canvas.

To follow along in Visual Studio, please download the Processing Sketchbook projection.

The finished sketch for this lesson can be found below:

int rows = 12;
int cols = 12;
int margin = 10;
int rowsSpace;
int colsSpace;
int totalBlocks = 144;
Block[] blocks = new Block[totalBlocks];
int width, height;
float targetX, targetY;
float pointerX, pointerY;
float sketchDiagonal;
 
void setup() {
  width = 500;
  height = 550;
  size(width, height);
  rowsSpace = ( width - margin ) / rows;
  colsSpace = ( height - margin) / cols;
  sketchDiagonal = width*width + height*height;
  sketchDiagonal *= .6;
  noStroke();
  smooth();
  targetX = width / 2;
  targetY = height / 2;
  pointerX = targetX;
  pointerY = targetY;
  int r = 255;
  int g = 0;
  int b = 255;
  int count = 0;
  for ( int x = 0; x < rows; x++) {
    for ( int y = 0; y < cols; y++ ) {
      Block block = new Block();
      block.x = margin + x*rowsSpace;
      block.y = margin + y*colsSpace;
      r = map(x, 0, rows, 0, 255);
      b = map(y, 0, cols, 0, 255);
      block.baseColor = color( r, g, b, 255);
      block.rotation = 0;
      blocks[count++] = block;
    }
  }
};
 
void draw() {
  background(0);
  pointerX += ( targetX - pointerX)*.16;
  pointerY += ( targetY - pointerY)*.16;
  for ( int i = 0; i < totalBlocks; i++) {
    float dx = blocks[i].x - pointerX;
    float dy = blocks[i].y - pointerY;
    float width = 1.0 - (dx*dx + dy*dy)/sketchDiagonal;
    float angle = Math.atan2(dy, dx);
    blocks[i].wide = width*colsSpace;
    blocks[i].rotation = angle; 
    blocks[i].render();
  }
};
 
void pointerMove(TouchEvent e){
  targetX = e.offsetX;
  targetY = e.offsetY;
};
 
class Block {
  float x = 0.0;
  float y = 0.0;
  float wide = 5.0;
  float rotation = 0.0;
  color baseColor = color(255,255,255,255);
  color detailColor = color(255,255,255,255);
  void render(){
    pushMatrix();
    translate( this.x, this.y);
    fill(this.baseColor);
    rotate(this.rotation);
    rect( 0, -1, this.wide, 2);
    fill(this.detailColor);
    ellipse(0, 0, 3, 3);
    popMatrix();
  }
}

Embed

Download

Download this episode

The Discussion

Add Your 2 Cents