Follow 2

Follow 2 based on code from Keith Peters.

A two-segmented arm follows the cursor position. The relative angle between the segments is calculated with atan2() and the position calculated with sin() and cos().


float[] x = new float[2];
float[] y = new float[2];
float segLength = 50;

void setup() {
  size(640, 360);
  strokeWeight(20.0);
  stroke(255, 100);
}

void draw() {
  background(0);
  dragSegment(0, mouseX, mouseY);
  dragSegment(1, x[0], y[0]);
}

void dragSegment(int i, float xin, float yin) {
  float dx = xin - x[i];
  float dy = yin - y[i];
  float angle = atan2(dy, dx);  
  x[i] = xin - cos(angle) * segLength;
  y[i] = yin - sin(angle) * segLength;
  segment(x[i], y[i], angle);
}

void segment(float x, float y, float a) {
  pushMatrix();
  translate(x, y);
  rotate(a);
  line(0, 0, segLength, 0);
  popMatrix();
}

Functions Used

stroke()

Sets the color used to draw lines and borders around shapes

Learn More
size()

Defines the dimension of the display window width and height in units of pixels

Learn More
pushMatrix()

Pushes the current transformation matrix onto the matrix stack

Learn More
sin()

Calculates the sine of an angle

Learn More
popMatrix()

Pops the current transformation matrix off the matrix stack

Learn More
setup()

The setup() function is run once, when the program starts

Learn More
strokeWeight()

Sets the width of the stroke used for lines, points, and the border around shapes

Learn More
cos()

Calculates the cosine of an angle

Learn More
rotate()

Rotates the amount specified by the angle parameter

Learn More
translate()

Specifies an amount to displace objects within the display window

Learn More
draw()

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called

Learn More
atan2()

Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis

Learn More
line()

Draws a line (a direct path between two points) to the screen

Learn More
background()

The background() function sets the color used for the background of the Processing window

Learn More