Processing Problem # 2

The next challenge will include you using both loops trigonometric functions, and time functions.

The program you wrote to make a figure was a linear program.  It began and it ended, and then it began again.  Each command only executed one time for every iteration through the "draw" void.

Today we include loops:  The first I will introduce is the WHILE loop. See the first (left) code below.  After x & y are set to 50 we start looping as long as y remains less than 500.  Notice that there is a second set of { } now to let the computer know exactly what to loop.  DO NOT FORGET to increment the count or else it will never stop.  Cut and paste this code into a window and play with it.  What is you increment y less?  or more?  What if you also increment x by some number?

Another thing you can incorporate into your code are the trig functions sin() and cos().  When going from rectangular coordinates (x, y) to polar coordinates (radius, theta) we need to do math.  P5*js only plots in x, y so we need to convert.  The math facts are:

x = radius * cos(theta); AND y = radius * sin(theta); 

see example below (middle)

We can also use an equation or equations to get new numbers rather than sin() or cos().  In the last example I used:        y = -x^2 - x + 2

Finally, I can use commands like second() and mouseX or mouseY commands change a function.  There are other timing functions here.

Your robotic assignment # 2 is to create a script that includes a time function that produces movement and also uses the trigonometric functions of sin() and cos().   Good luck.

Simple Loop

 

function setup() {

  createCanvas(400, 400);

}

 

function draw() {

  background(220);

  x = 50;

  y = 50;

  while (y < 400){

line(x,y,x+300,y);

y = y + 50;

        }

}


Polar to Rectangular

 

function setup() {

  createCanvas(400, 400);

}

 

function draw() {

  background(220);

  r = 100;     // this is radius

  t = 0;  // this is theta

  dt = 2*3.14159/7; // how much change in angle

  while (t<2*3.14159){   // until 2*PI

x = r * cos(t);

y = r * sin(t);

line(200,200,200+x,200+y);

t = t + dt;

}

}

Butterfly Algebra

 

function setup() {

  createCanvas(400, 400);

}

 

function draw() {

  background(220);

  x = -20;

  while (x<20){

y = -x*x - x + 20;

x1 = x * 10;

line(200,100,205+x1,360+y); 

x = x + 1;

  }

}