Rewrite Example 5-6 so that the ball not only moves horizontally, but vertically as well. Can you implement additional features, such as changing the size or color of the ball based on certain conditions? Can you make the ball speed up or slow down in addition to changing direction?
Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Exercise 5-9: Rewrite Example 5-6 so that the ball not only moves
// horizontally, but vertically as well. Can you implement additional
// features, such as changing the size or color
// of the ball based on certain conditions? Can you make the ball speed
// up or slow down in addition to changing direction?

float x = 0;
float y = 0;
float xspeed = 2.2;
float yspeed = 1.5;
float r = 32;

void setup() {
  size(200,200);
  smooth();
}

void draw() {
  background(255);

  // Add the current speed to the x location.
  x = x + xspeed;
  y = y + yspeed;

  // Remember, || means "or."
  if ((x > width) || (x < 0)) {
    // If the object reaches either edge, multiply speed by -1 to turn it around.
    xspeed = xspeed * -1;
    r = 64;
  }
  
   // Remember, || means "or."
  if ((y > height) || (y < 0)) {
    // If the object reaches either edge, multiply speed by -1 to turn it around.
    yspeed = yspeed * -1;
    r = 64;
  }

  // Display circle at x location
  stroke(0);
  fill(175);
  ellipse(x,y,r,r);
  
  r = constrain(r-2,32,64);
  
}

2 Comments

»

  1. r = constrain(r-2,32,64);

    I can’t unterstand why the first value of constrain() is not “r” but “r-2″.
    I changed the value “r-2″ to “r”, then the ball size went up to 64 when it touch the screen and didn’t come back to 32.
    Please explain me.. the roll of constrain() in this example!

    Comment by P3HO — February 3, 2010 @ 1:51 am

  2. It would probably be easier to understand if I wrote the code like this:

    r = r - 2;
    r = constrain(r,32,64);
    

    In other words, we want r to always get smaller, but never go below 32 (or above 64). The constrain function allows you to perform a mathematical operation at the same time and decrease the value or r, while constraining it.

    r = constrain(r-2,32,64);
    

    Comment by Daniel Shiffman — February 3, 2010 @ 6:52 pm

Leave a comment