learn creative coding: begin programming with the processing language

Post on 02-Nov-2014

99 Views

Category:

Technology

4 Downloads

Preview:

Click to see full reader

DESCRIPTION

Beginner tutorial for the Processing programming language Given at Long Beach Indie Digital Edutainment Conference 8.30.14

TRANSCRIPT

Learn Creative CodingBegin Programming with the Processing Language

W. Michelle HarrisRochester Institute of Technologyhttp://people.rit.edu/wmhicsLong Beach Indie Digital Edutainment Conference 8.30.14

http://processing.org

How do you communicate a design?Imagine you opened your favorite

drawing app, created a new document, and drew a straight line and a circle.

How would you type out complete instructions for re-creating your drawing (no illustrations allowed)?

Take a few minutes to ponder this…

Do they need to know:1. Drawing app choice2. Dimensions of

canvas3. Canvas color4. Line drawing tool5. Line stroke color,

thickness6. Line drag start and

stop coordinates7. Circle drawing tool

8. Circle stroke color, thickness

9. Circle fill color and pattern

10.Circle bounding box drag start and stop coordinates

-or- Circle center coordinate and radius

11.?

Line + circle in drawing app, then in Processing code

Prepare the Canvas1. Drawing app choice: new Processing

sketch!2. Dimensions of canvas3. Canvas color

Processing environment

A program written in Processing is called a sketch.Type your sketch in this space. Text is colored automatically according to its purpose. Status feedback area

Console area for text output and too-detailed error messages.

Current cursor line number in this sketch.

A warning before we code:Processing is as picky as your 8th grade Language Arts teacher

Order, spelling, capitalization, and punctuation matter. Mistake => won’t go at all, or goes wonky.

point(30, 75); // point() parameters: x, y

Function name, then parentheses with any parameters inside separated by commas. End with a semicolon.

Each instruction can start and be interspersed with spaces, tabs, and even line breaks for readability.

Entire lines can be blank for readability, too.

Prepare the Canvas/* When you make this new canvas, size it 300 pixels wide, and 250 pixels tall. */size(300, 250);

/* Set the canvas background color to white. */background(255);

size(widthPix, heightPix); // in pixels background(grayValue); // 0.0 – 255.0 // Alternatively, background(red, green, blue);

Prepare settings for the Line4. Line drawing tool? There is only one

choice ;)5. Line stroke color, thickness

Prepare settings for the Line/* Set the drawing stroke color to blue */stroke(128, 119, 251);

/* Set the drawing stroke thickness to 5 pixels */strokeWeight(5);

stroke(redVal, blueVal, greenVal); //0.0 – 255 strokeWeight(widthPix);

Draw the Line6. Line drag start and stop coordinates

Draw the Line/* Start line at coordinates x:135, y:213, and end the line at coordinates x:287, y:66. */line(135, 213, 287, 66);

line(x1, y1, x2, y2);

Save and Run your sketch.

Prepare settings for the Circle7. Circle drawing tool: Choose drawing

mode – corner-to-corner? Start coordinates & width & height (default mode in Processing)?

8. Circle stroke color, thickness9. Circle fill color and pattern

Prepare settings for the Circle/* Set the drawing fill color to black */fill(0);

/* We don’t want any drawing stroke */noStroke();

fill(grayValue); //0–255 fill(red, blue, green); noStroke();

Draw the Circle10.From circle center drag out width

and height

Draw the Circle/* Center ellipse at coordinates x:110, y:110, and make width 100, height 100. */ellipse(110, 110, 100, 100);

ellipse(x, y, width, height);

Save and Run your sketch.

One question you might haveSometimes, we gave Processing a

single grayscale color value, and sometimes we gave it three RGB color values. Can both be right?

stroke(): 6 ways to color

stroke(gray);stroke(red, green, blue);stroke(#RRGGBB);stroke(gray, alpha);stroke(red, green, blue, alpha);stroke(#RRGGBB, alpha);

Processing knows which version of the function you want by the number and type of parameters within its parentheses.Many of the built-in functions work this way.

Start exploring(the Processing Reference too)

Some primitive 2D shapes:line(), triangle(), quad(), rect(), ellipse(), arc()

Setting shape attributes:fill(), noFill() stroke(), noStroke()strokeWeight(), strokeCap()ellipseMode(), rectMode()

Section goals1. If I design a composition with simple

shapes, I can remake it in Processing.

2. I know how to use different kinds of color parameters to make those shapes.

3. I know how to use the Processing Reference to find out details about functions.

Helpful hintsPay attention when auto-coloring does

NOT do what you expected.Get familiar with what kinds of errors

cause which messages and where (make mistakes on purpose to check).

Processing will stop compiling your code at the first syntax error it encounters. Watch the cursor for where it thinks that error occurred.

Next: Five Things

1. /* Comments */ and //Comments

2. Math expressions3. Code blocks for animation4. Tracking the mouse

1. Which would you rather troubleshoot?size(300, 250);background(255);

stroke(128, 119, 251);strokeWeight(5);line(135, 213, 287, 66);

fill(0);noStroke();ellipseMode(CORNERS);ellipse(59, 60, 159, 160);

/* Canvas prep */size(300, 250);background(255); // white bg

/* Line prep */stroke(128, 119, 251); // blue linestrokeWeight(5);/* Make the line */line(135, 213, 287, 66);

/* Circle prep */fill(0); // black fillnoStroke();/* Make the circle */ellipse(110, 110, 100, 100);

1. Comments, 2 ways//Single line comment

/* Multiline comments can take up all the space

you need as long as they end with… */

/* Canvas prep */size(300, 250);background(255); // white

/* Line prep */stroke(128, 119, 251); // bluestrokeWeight(5);// Make the lineline(135, 213, 287, 66);

2. How many little equations would you need to figure to position all the shapes?

An alternative: substitute a math expression for a person-calculated value.

2. Math expressions as function parameters. Code before...

+ plus- minus* multiplied by/ divided by% modulo remainder

size(400, 300);

// headellipse(200, 150, 100, 100);

//eyesellipse(180, 150, 20, 30);ellipse(220, 150, 20, 30);

2. Math expressions as function parameters. Code lazier.

+ plus- minus* multiplied by/ divided by% modulo remainder

size(400, 300);

// headellipse(200, 150, 100, 100);

//eyesellipse(200 - 20, 150, 20, 30);ellipse(200 + 20, 150, 20, 30);

2. Math expressions as function parameters. Code laziest.

+ plus- minus* multiplied by/ divided by% modulo remainder

Helpful built-in property variables:

width //canvas width

height //canvas height

size(400, 300);

// head – centered on canvasellipse(width/2, height/2,

100, 100);

//eyesellipse((width/2 – 20), height/2,

20, 30);ellipse((width/2 + 20), height/2,

20, 30);

3. An analogy: running

http://www.blackgirlsrun.com/partner-up

3. To animate runnersOne-time Setup steps:

1. Size the canvas2. Set the desired frame update rate

Perpetually loop these Draw steps:1. Color the canvas (to erase the prior

frame)2. Draw scenery elements3. Draw next sprite in cycle of runner #14. Draw next sprite in cycle of runner #25. Render pixels from 1-4.

3. Blocks: grouping/herding codeA block of code is any code enclosed in { }. One useful feature of blocks: they can be nested within each other.

block1 { // a block of code opensstatement;block2 { // a nested block of code opens

statement;statement;

} // end of block2 statement;

} // end of block1block3 { // a block of code opens

statement;} // end of block3

3. To animate in Processingvoid setup() { // Initialization code goes here

size(400, 3oo);frameRate(24); // Frames per second. Default max is

60.}

void draw() { // Code to run forever - animate - goes here

background(255);drawScenery(); // this function doesn’t existdrawNextRunner1(); // this function doesn’t existdrawNextRunner2(); // this function doesn’t exist/* At the end of draw(), Processing renders the new pixels produced in this block. */

}

3. Try this in Processing// Pointy sketchsize(400, 300); strokeWeight(5);stroke(0);

background(255);point(200, 150);

// Pointy sketchvoid setup() {

size(400, 300); strokeWeight(5);stroke(0);

}

void draw() { // animate!

background(255);point(200, 150);

}

4. Now edit it}

void draw() { // animate!

background(255);point(200,

150);}

}

void draw() { // animate!

background(255);//point(200, 150);point(mouseX,

mouseY);}mouseX and mouseY are built-in property variables of the

sketch like height and width (in the same way that point() is a built-in function).

4. What’s the difference?void setup() {

size(400, 3oo); strokeWeight(5);

stroke(0);}

void draw() { // animate!background(255);point(mouseX,

mouseY);}

void setup() {size(400, 3oo);

strokeWeight(5);stroke(0);background(255);

}

void draw() { // animate!// background(255);point(mouseX,

mouseY);}

4. Edit for variation with pmouseX and pmouseY

void draw() { // animate!// background(255);point(mouseX,

mouseY);}

void draw() { // animate!// background(255);// point(mouseX,

mouseY);line(pmouseX,

pmouseY, mouseX, mouseY);}

pmouseX and pmouseY are built-in property variables for the position of the mouse in the frame draw()n just prior to the current one.

3 Things you’re doing now

1. draw() {} code blocks for animation2. Math expressions with built-in

property variables3. Mouse property variables for

interaction

Data typesIn Processing, data are categorized by type.Three useful data types:int whole numbers (-230548, 0, 45)float decimal numbers (-4.3, 30984.349)String sequence of characters ("Hi, Ebony!")

Making our own Variables

What if I want to use that hard-calculated value again?The answer: Let's create our own variable and store it there.

VariablesContainer for storing some piece of data. A

variable is a way for the program to remember.

Each variable has a name We make up almost any name we want within the

rules (but it should make sense!) We can use the name to refer to that piece of data

The value might change during the execution of the program. Hence, “variable.” The variable actually points to a specific physical

memory location in RAM.

Some redundancies here...void setup() { size(400, 300); frameRate(5); colorMode(HSB);}

void draw() { fill(frameCount % 256, 255, 255); triangle(0, 0, mouseX, mouseY, dist(pmouseX, pmouseY, mouseX, mouseY), dist(pmouseX, pmouseY, mouseX, mouseY));}

float mdistance; // Declare the variable type and name void setup() { size(400, 300); frameRate(5); colorMode(HSB);}

void draw() { /* Assign mdistance to store the distance between

the latest and just-previous mouse positions. */ mdistance = dist(pmouseX, pmouseY,

mouseX, mouseY);

fill(frameCount % 256, 255, 255); triangle(0, 0, mouseX, mouseY, mdistance, mdistance);}

float mdistance; // Declare the variable type and name void setup() { size(400, 300); frameRate(5); colorMode(HSB);}

void draw() { /* Assign mdistance to store the distance between

the latest and just-previous mouse positions. */ mdistance = dist(pmouseX, pmouseY,

mouseX, mouseY);

fill(frameCount % 256, 255, 255); triangle(0, 0, mouseX, mouseY, mdistance, mdistance);}

Before we use a variable, we need to declare it.To declare it, use the keyword for the type of data it will hold:

String instructions;int shapeNumber;

At this point, the variable exists, but doesn’t hold a value yet. We’ve simply informed the computer that we intend to use a variable by that name and of that data type.

float mdistance; // Declare the variable type and name void setup() { size(400, 300); frameRate(5); colorMode(HSB);}

void draw() { /* Assign mdistance to store the distance between

the latest and just-previous mouse positions. */ mdistance = dist(pmouseX, pmouseY,

mouseX, mouseY);

fill(frameCount % 256, 255, 255); triangle(0, 0, 0, height, mdistance, mdistance);}

Why is this variable declared as type float?Why not type int?

void draw() { /* Assign mdistance to store the distance between

the latest and just-previous mouse positions. */ mdistance = dist(pmouseX, pmouseY,

mouseX, mouseY);

fill(frameCount % 256, 255, 255); triangle(0, 0, 0, height, mdistance, mdistance); triangle(width, height, width, 0, mdistance, mdistance);}

Give a variable a value with an assignment statement – it uses an equal sign.

shapeNumber = frameCount - 1;

The action goes right to left: the value (frameCount – 1) replaces any current value in the variable shapeNumber.

float mdistance; // Declare the variable type and name void setup() { size(400, 300); frameRate(5); colorMode(HSB);}

void draw() { /* Assign mdistance to store the distance between

the latest and just-previous mouse positions. */ mdistance = dist(pmouseX, pmouseY,

mouseX, mouseY);

fill(frameCount % 256, 255, 255); triangle(0, 0, mouseX, mouseY, mdistance, mdistance);}

Once the variable is declared and a value assigned, we can use the variable anywhere we would have used the value:

point(shapeNumber, height/2);

float mdistance; // Declare the variable type and name void setup() { size(400, 300); frameRate(5); colorMode(HSB);}

void draw() { /* Assign mdistance to store the distance between

the latest and just-previous mouse positions. */ mdistance = dist(pmouseX, pmouseY,

mouseX, mouseY);

fill(frameCount % 256, 255, 255); triangle(0, 0, mouseX, mouseY, mdistance, mdistance);}

Rules for variable namesMust start with a letterMay NOT contain spaces (only one “word”)May contain numbers and _underscores_camelCase

Start with lower case letter Opt: next words start with upper case (easier to

read)Tip: Longer is often better for future

comprehension selectedCar instead of sc or selCar or

selectCar

You can declare and assign an initial value in one statement// Circles along the diagonalint shapeNumber;int randomSize;

void setup() { size(200, 200); ellipseMode(CENTER); shapeNumber = 1;}

void draw() { randomSize = int (random(5, 50)); ellipse(shapeNumber, shapeNumber, randomSize, randomSize); shapeNumber = shapeNumber + 1;}

// Circles along the diagonalint shapeNumber = 1;int randomSize;

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

void draw() {

Statement review

String instructions;

void setup() {size(200, 500);instructions = "Swoosh your

mouse";}void draw() { // points follow mouse

point(mouseX, mouseY);}/* On click, instructions print in console */void mousePressed() {

println(instructions);}

1. Variable declaration2. Code block3. Function call4. Assignment statement5. Comments

and now 6...

If-else [conditional] blocks

Instead of always following one path, let the computer make a choice based on the current outcome of some condition.

Decisions in computereseCarbon-based life

If it is raining hard enough to bother me outside, maybe I'll put on a hat or carry an umbrella – depends on my mood.

Silicon-based machines

rainIntensity = calcIntensity();if (rainIntensity > 3) {

wearRainCover();}

wearRainCover

Decisions in computereseCarbon-based life

If it is raining hard enough to bother me outside, maybe I'll put on a hat or carry an umbrella – depends on my mood.Otherwise, I'm wearing my new shades.

Silicon-based machines

rainIntensity = calcIntensity();if (rainIntensity > 3) {

wearRainCover();} else {

wearSunCover();}

If-else block

if (rainIntensity > 3) { // do this if true

wearRainCover();} else { // otherwise do this

wearSunCover();}

Expression that can evaluate to true or false

rain

sun

If-else blockif (Boolean expression) { // do this if true

statement;statement;

} else { // otherwise do this (opt) statement;

statement;statement;

}

Expression that can evaluate to true or false

Start with creeping circle...int x = -20;

void setup() { ellipseMode(CENTER);}void draw() { ellipse(x, height/2, 20, 20); x = x + 1;}

After the circle gets beyond the right edge, we will never see it again.

Let's change

that.

Proceed with cycling circle

… }

void draw() { ellipse(x, height/2, 20, 20); x = x + 1; // If circle gets too far… if (x > (width + 20)) { //cycle! x = -20; }}

… }

void draw() { ellipse(x, height/2, 20, 20); x = x + 1;

/* When circle goes off right edge, start it back at left edge again.*/}

Boolean expressions with comparison operators

true

45 == 4510 < 10010 > -399 <= 10099 >= 98100 != 88

Do block

false

45 == 3010 < -310 > 8899 <= 3099 >= 100100 != 100

Skip block

Reserved word representing a logical value.

Equal?Less?Greater?Less or equal?Greater or equal?Not equal?

Points, black circles, and red rects depending on conditional expressions.

void setup() { ellipseMode(CENTER); rectMode(CENTER);}

void draw() { if (mouseX < 10) { // far left ellipse (width/2, mouseY, 20, 20); }

if (mouseX < width/2) { // left side stroke(0); // black stroke } else { // right side stroke(255,0,0); //red stroke } point(mouseX, mouseY); if (mouseX >= width - 10) { // far right rect (width/2, mouseY, 20, 20); }}

Boolean variablesboolean isFirstClick = true;

void setup() { ellipseMode(CENTER);}

void draw() { if (isFirstClick) { ellipse(mouseX, mouseY, 20, 20); } else { point(mouseX, mouseY); }}

void mousePressed() { isFirstClick = false; strokeWeight(4); stroke(150, 0, 150); //purple}

More complex expressions

Logical operators:a || b || c // orif any is true

a && b && c // andonly if all true

!a // notif not true

boolean myTest;

myTest = (mouseY < 0) || (mouseY >

height);

// mousePressed and keyPressed// are built-in boolean variables.myTest = mousePressed &&

keyPressed;

// key (built-in char variable) returns// most recent keyboard key valuemyTest = !((key == 'q') || (key == 'Q'));

More complex expressions

Assume height=200

mouseY myTest-10 true0

false50

false200 false201 true

boolean myTest;

myTest = (mouseY < 0) || (mouseY >

height);

// Would otherTest ever be true?boolean otherTest;

otherTest = (mouseY < 0) && (mouseY >

height);

More complex expressions

boolean myTest;

// mousePressed and keyPressed// are built-in boolean variables.myTest = mousePressed &&

keyPressed;

// What's the difference?boolean otherTest;

otherTest = mousePressed ||

keyPressed;

keyPressed

mousePressed

myTest

true true true

true false false

false true false

false false false

More complex if-else block useboolean isFirstClick = true;

void setup() { ellipseMode(CENTER);}

void draw() { if (isFirstClick) { ellipse(mouseX, mouseY, 20, 20); } else if (mousePressed) { line(pmouseX, pmouseY,

mouseX, mouseY); } else { point(mouseX, mouseY); }}

circle

line point

More complex if-else block useboolean isFirstClick = true;

void setup() { ellipseMode(CENTER);}

void draw() { if (isFirstClick) { ellipse(mouseX, mouseY, 20, 20); } else if (mousePressed) { line(pmouseX, pmouseY,

mouseX, mouseY); } else { point(mouseX, mouseY); }}

void mousePressed() { isFirstClick = false; strokeWeight(4); stroke(150, 0, 150); //purple}

void keyPressed() { if (key =='c' || key == 'C') { background(200); //clear bg } if (key =='q' || key == 'Q') { exit(); //quit }}

Two things1. Global vs Local variables2. Iteration with while loops

1. Global (what we've been doing) versus Local variables

variable scope

1. Global variables (used so far)Declare outside/beyond any blockKnown throughout allPersists from declaration throughout run of app

float mdistance;

void setup() { size(400, 300); frameRate(5); colorMode(HSB); mdistance = 10;}

void draw() { mdistance = dist(pmouseX, pmouseY,

mouseX, mouseY); fill(frameCount % 256, 255, 255); triangle(0, 0, 0, height,

mdistance, mdistance); triangle(width, height, width, 0,

mdistance, mdistance);}

// no mdistance exists

void setup() { size(400, 300); frameRate(5); colorMode(HSB); // no mdistance exists}

void draw() { int mdistance = dist(pmouseX, pmouseY,

mouseX, mouseY); fill(frameCount % 256, 255, 255); triangle(0, 0, 0, height,

mdistance, mdistance); triangle(width, height, width, 0,

mdistance, mdistance);} // no mdistance exists

Declare inside a blockExists only inside the blockPersists from declaration to end of current

run of the block

1. Local variables

1. What's the difference?// Global "count"int count = 0; void setup() { size(200,200);}void draw() { count = count + 1; background(count); println(count);}

// Local "count"void setup() { size(200,200);}void draw() { int count = 0; count = count + 1; background(count); println(count);}

1. What's the difference?// Global "count"int count = 0; void setup() { size(200,200);}void draw() { count = count + 1; background(count); println(count);}

// Local "count"void setup() { size(200,200);}void draw() { int count = 0; count = count + 1; background(count); println(count);}

1. Is count local or global? Would this declaration work?

void setup() { size(200,200); int count = 0; }void draw() { count = count + 1; background(count); println(count);}

1. When should you use local vs. global?void mousePressed() {int count = frameCount % 255;background(count, 255, 255); }void draw() { int count = mouseX + 40; fill(count); triangle(0, 0, width, height,

0, height);}

Global if…Need to use in multiple blocks.Need to persist beyond a single run of a block.

Local if…Alright/need to re-birth each run of a block (like both cases in this example)

2. Iteration with while loops

Doing it and doing it and doing it well.

2. Conditional to IterationlocationX = 0;if (locationX < width) {

point(locationX, 40);// move pointlocationX = locationX +

1;}// do more stuff

Draw &

move pt

2. Conditional to IterationlocationX = 0;while (locationX < width) {

point(locationX, 40);// move pointlocationX = locationX +

1;} // exit loop only if condition false// do more stuff

Draw &

move pt

2. Conditional to Iteration

Three keys to this loop:

1. Prepare variable before

2. Test condition with variable

3. Change variable during repetition

locationX = 0;while (locationX < width) {

point(locationX, 40);// move pointlocationX = locationX

+ 1;} // exit loop if condition false// do more stuffIf you don't ensure the while condition will at some point become true, the program won't ever escape the loop (until you kill it :O).

2. Iterating legs//Prep to draw legs - vertical lines 100px longstrokeWeight(4);// First leg just beyond left edge of body (100).// Draw legs spaced every 15px until// beyond right edge of body, which is at 300.line(110, 100, 110, 200);//place next leg, 2line(125, 100, 125, 200);//place next leg, 3line(140, 100, 140, 200);

//place next leg, 13line(290, 100, 290, 200);

size(400, 300);stroke(0);strokeWeight(1);fill(0);

//draw body as rectanglerectMode(CORNER);rect(100, 130, 200, 40);

//draw head as ellipseellipseMode(CENTER);ellipse(80, 150, 50, 30);

What changes and what stays the same? Is there a pattern to the change?Can we use a variable to simplify?

2. Iterating legs

//Prep to draw legs - vertical lines 100px longstrokeWeight(4);// First leg just beyond left edge of body (100).// Draw legs spaced every 15px until// beyond right edge of body, which is at 300.legX = 110;

line(legX, 100, legX, 200);//place next leg, 2legX = legX + 15;line(legX, 100, legX, 200);

//place next leg, 13legX = legX + 15;line(legX, 100, legX, 200);

int legX; //x position of leg

size(400, 300);stroke(0);strokeWeight(1);fill(0);

//draw body as rectanglerectMode(CORNER);rect(100, 130, 200, 40);

//draw head as ellipseellipseMode(CENTER);ellipse(80, 150, 50, 30);

2. Iterating legs

//Prep to draw legs - vertical lines 100px longstrokeWeight(4);// First leg just beyond left edge of body (100).// Draw legs spaced every 15px until// beyond right edge of body, which is at 300.legX = 110;

line(legX, 100, legX, 200);//place next leg, 2legX = legX + 15;line(legX, 100, legX, 200);

//place next leg, 13legX = legX + 15;line(legX, 100, legX, 200);

int legX; //x position of leg

size(400, 300);stroke(0);strokeWeight(1);fill(0);

//draw body as rectanglerectMode(CORNER);rect(100, 130, 200, 40);

//draw head as ellipseellipseMode(CENTER);ellipse(80, 150, 50, 30);

Repetitive code that changes

variable.

Prepared variable

2. Iterating legs

// Prepare to draw legs strokeWeight(4); // First leg just beyond left edge of body (100). legX = 110;} // end setup

// Draw legs spaced every 15px until// beyond right edge of body, which is at 300.void draw() { if ( ??? ) { // within body? line(legX, 100, legX, 200); //place next leg legX = legX + 15; }}

int legX; //x position of leg

void setup() { size(400, 300); stroke(0); strokeWeight(1); fill(0);

//draw body as rectangle rectMode(CORNER); rect(100, 130, 200, 40);

//draw head as ellipse ellipseMode(CENTER); ellipse(80, 150, 50, 30);

Test condition?Repetitive code

that changes variable.

Prepared variable

2. Iterating legs

// Prepare to draw legs strokeWeight(4); // First leg just beyond left edge of body (100). legX = 110;} // end setup

// Draw legs spaced every 15px until// beyond right edge of body, which is at 300.void draw() { if (legX < 300) { // within body? line(legX, 100, legX, 200); //place next leg legX = legX + 15; }}

int legX; //x position of leg

void setup() { size(400, 300); stroke(0); strokeWeight(1); fill(0);

//draw body as rectangle rectMode(CORNER); rect(100, 130, 200, 40);

//draw head as ellipse ellipseMode(CENTER); ellipse(80, 150, 50, 30);

Test condition

2. Iterating legs

// Prepare to draw legs strokeWeight(4); // First leg just beyond left edge of body (100). legX = 110;

// Draw legs spaced every 15px until // beyond right edge of body, which is at 300. while (legX < 300) { // within body? line(legX, 100, legX, 200); //place next leg legX = legX + 15; }

noLoop(); //Don't need to do looping draw{}} // end setup

void setup() { int legX; //x position of leg

size(400, 300); stroke(0); strokeWeight(1); fill(0);

//draw body as rectangle rectMode(CORNER); rect(100, 130, 200, 40);

//draw head as ellipse ellipseMode(CENTER); ellipse(80, 150, 50, 30);

What goes in the blanks?size(200, 200);int y = 0;while ( _____ ) { line ( ___, ___, ____, ___ ); y = ___________ ;}

What goes in the blanks?size(200, 200);background(255);float w = ___ ;while ( ______ ) { fill( ___ ); ellipse( ___, ___, ___, ___ ); ___ = ________ 20;}

Functions

Why herd code into functions?ModularitySmaller chunks are easier to read/manage/update

ReusabilityYou can write a chunk once, and use from multiple places

How could we break up draw?

float xSpeed;float x, y;

void setup() { size(200, 200); ellipseMode(CENTER); rectMode(CORNER); xSpeed = 1; // behavior if -1? x = 10; // start inside left edge y = height/2; // stay at middle}

void draw() { //fill canvas with translucent rect fill(255, 60); rect(-1, -1, width+1, height+1); // draw the ball fill(255, 0, 0); ellipse(x, y, 20, 20);

//at edge? Bounce the ball if ((x > width - 10) || (x < 10)) { xSpeed = xSpeed * -1; //reverse }

// move the ball x = x + xSpeed;}

How could we break up draw?

float xSpeed;float x, y;

void setup() { size(200, 200); ellipseMode(CENTER); rectMode(CORNER); xSpeed = 1; // behavior if -1? x = 10; // start inside left edge y = height/2; // stay at middle}

void draw() { //fill canvas with translucent rect fill(255, 60); rect(-1, -1, width+1, height+1); // draw the ball fill(255, 0, 0); ellipse(x, y, 20, 20);

//at edge? Bounce the ball if ((x > width - 10) || (x < 10)) { xSpeed = xSpeed * -1; //reverse }

// move the ball x = x + xSpeed;}

How could we break up draw?

float xSpeed;float x, y;

void setup() { size(200, 200); ellipseMode(CENTER); rectMode(CORNER); xSpeed = 1; // behavior if -1? x = 10; // start inside left edge y = height/2; // stay at middle}

void draw() { //fill canvas with translucent rect fill(255, 60); rect(-1, -1, width+1, height+1); // draw the ball fill(255, 0, 0); ellipse(x, y, 20, 20);

//at edge? Bounce the ball if ((x > width - 10) || (x < 10)) { xSpeed = xSpeed * -1; //reverse }

// move the ball x = x + xSpeed;}

screenCanvas();

drawBall();

bounceBall();

moveBall();

How could we break up draw?

// draw the ballvoid drawBall() { fill(255, 0, 0); ellipse(x, y, 20, 20);}

//at edge of canvas? Bounce the ballvoid bounceBall() { if ((x > width - 10) || (x < 10)) { xSpeed = xSpeed * -1; //reverse }}

// move the ball by xSpeedvoid moveBall() { x = x + xSpeed;}

…void draw() { screenCanvas(); drawBall(); bounceBall(); moveBall();}

//fill canvas with translucent rectvoid screenCanvas() { fill(255, 60); rect(-1, -1, width+1, height+1); }

Anatomy of function calls (review) and blocks (new)

void mousePressed() {functionName(arg1, arg2, arg3);

}

void functionName(int param1, int param2, boolean param3) {

// Statements doing something like…if (param3) {

point(param1, param2);}

}

Arguments can be passed to the function to be used as parameter variables.

Drawing faces flexiblyvoid setup() { size(500, 500); }void draw() {

drawFace(mouseX, mouseY, 100);}void drawFace(int faceX, int faceY, int radius) {

ellipse(faceX, faceY, radius, radius);ellipse((faceX - radius/5), faceY, radius/5,

radius/3);ellipse((faceX + radius/5), faceY, radius/5,

radius/3);}

top related