Skip to content

Instantly share code, notes, and snippets.

@multimentha
Created January 9, 2018 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save multimentha/2859eabc04c7788b1fe984df255b902c to your computer and use it in GitHub Desktop.
Save multimentha/2859eabc04c7788b1fe984df255b902c to your computer and use it in GitHub Desktop.
Learning Processing Example 7-4 Suggested Change Corrected (2nd edition, p. 123)
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com
// Example 7-3: Bouncing ball with functions
// Declare all global variables (stays the same)
int x = 0;
int speed = 1;
// Setup does not change
void setup() {
size(480, 270);
}
void draw() {
background(255);
move(); // Instead of writing out all the code about the ball is draw(), we simply call three functions. How do we know the names of these functions? We made them up!
bounce();
// display(); // display ball, it's the original
display_smiley(); // display smiley instead
}
// Where should functions be placed?
// You can define your functions anywhere in the code outside of setup() and draw().
// However, the convention is to place your function definitions below draw().
// A function to move the ball
void move() {
// Change the x location by speed
x = x + speed;
}
// A function to bounce the ball
void bounce() {
// If we’ve reached an edge, reverse speed
if ((x > width) || (x < 0)) {
speed = speed * - 1;
}
}
// A function to display the ball
void display() {
stroke(0);
fill(175);
ellipse(x,height/2,32,32);
}
// A function to display a rectangular smiley instead
void display_smiley() {
float y = height/2; // this declaration of Y is needed but not printed in the book!
background(255);
rectMode(CENTER);
noFill();
stroke(0);
rect(x,y,32,32); // will fail without declaration of Y
fill(255);
rect(x-4, y-4, 4, 4); // will fail without declaration of Y
rect(x+4, y-4, 4, 4); // will fail without declaration of Y
line(x-4, y+4, x+4, y+4); // will fail without declaration of Y
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment