Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 5-9: Simple Gravity

float x = 100;   // x location of square
float y = 0;     // y location of square

float speed = 0;   // speed of square

// A new variable, for gravity (i.e. acceleration).   
// We use a relatively small number (0.1) because this accelerations accumulates over time, increasing the speed.   
// Try changing this number to 2.0 and see what happens.
float gravity = 0.1;  

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

}

void draw() {
  background(255);

  // Display the square
  fill(175);
  stroke(0);
  rectMode(CENTER);
  rect(x,y,10,10);
  
  // Add speed to location.
  y = y + speed;
  
  // Add gravity to speed.
  speed = speed + gravity;
  
  // If square reaches the bottom
  // Reverse speed
  if (y > height) {
    // Multiplying by -0.95 instead of -1 slows the square down each time it bounces (by decreasing speed).  
    // This is known as a "dampening" effect and is a more realistic simulation of the real world (without it, a ball would bounce forever).
    speed = speed * -0.95;  
  }
}








  • rasco

    Hi, I am new into physiscs simulations but I have the same problem, which appears here. The ball /rectangle here/ begins oscilate at the bottom of scene. or in my sometimes it falls through it deeper and deeper. how to get rid of it? is there any trick?

    thanks a lot

    rasco

  • admin

    Sometimes if the shape goes below the window, turns around, but does not return to the window, it can get stuck (since the code would tell it to turn around again, moving further off the screen.) A quick way to fix that is to just reset the location, i.e.:

    if (y > height) {
    y = height;
    speed = speed * -0.95;
    }

  • http://subpixels.com subpixel

    One way to deal with the small oscillation is to test if the speed is smaller than some number you determine is close enough to zero when “bouncing”.

    For example: (please excuse use my use of “_” for indenting)

    if (y > height) {
    __ y = height;
    __ if ( speed < 1 ) // determine a minimum value acceptable to you by experimentation
    ____ speed = 0;
    __ else
    ____ speed = speed * -0.95;
    }

  • http://www.vspline.com Abdul

    I managed to implement a simple friction (decrementing the x speed when y reaches a certain value, the “ground” plane) and using the same technique have the bounces with the floor being counted. chuffed that I got this working!

    I am really pleased with this book and with processing as a creative language!

  • Thiago Pimentel

    I wanted to have a larger view of the values “y” and “speed” assume over the time to better understand the gravity simulation and managed to add some lines of code in order to get an output. At first, I put a “println(“y: ” + y + ” speed: ” + speed);” at the end of the sketch but I thought it was not enough once the output from the console only shows a few lines of these values after the sketch is stopped. For my surprise, I was glad to realize that I anticipated what is covered at the chapter on debugging! So I thought it would be better to get a text file with the values without the space constraints of the console. I only had the slightest idea on how to do that once my previous programming experience was very narrow and at this point of the book anything related to this problem was covered. I struggled to find out a solution and skipped some chapters in the hope of discovering how to get this done. Moving back and forth throughout the book I stuck with a few pages from the chapters on arrays and strings, and with the help of the Processing reference, I came up with the following solution:

    float x = 100;
    float y = 0;
    
    float speed = 0;
    float gravity = 0.1;
    
    int i = 0;
    
    String[] sy = new String[4000];
    String[] sspeed = new String[4000];
    String[] values = new String[4000];
    
    void setup() {
      size(200, 200);
      for (int i = 0; i < sy.length; i++) {
        sy[i] = "";
        sspeed[i] = "";
        values[i] = "";
      }
    }
    
    void draw() {
      background(255);
      
      fill(0);
      noStroke();
      rectMode(CENTER);
      rect(x, y, 10, 10);
      
      y = y + speed;
      
      speed = speed + gravity;
      
      if (y > height) {
    
        speed = speed * -0.95;
      }
      
      sy[i] = str(y);
      sspeed[i] = str(speed);
      values[i] = "y: " + sy[i] + " speed: " + sspeed[i];
      i = i + 1;
      if (i == 3000) {
      saveStrings("values.txt", values);
      }
    }
    

    If you are going to give this code a shot, I recommend you to keep the sketch folder open and wait a little until the file “values.txt” appears, and then, you are free to stop the sketch. Undoubtedly this is not the most elegant solution, but it worked fine for me. Hopefully it will be helpful for those who may be curious on how these values change and it may serve as an alternative suggestion to help debug your codes (and it’s my very hope that Mr. Shiffman incorporates my humble solution in future editions of the book).

    One important thing is worth of notice here: although professor Shiffman recommends us to read the book in a linear fashion until, at least, the end of chapter 9 (and it has been a delightful read thus far =), it’s important to keep in mind that sometimes a more flexible approach urges the necessity to be used in conjunction (not substitute) with the more traditional and gradual path. By the way, I will continue to study this book without skipping any word.

  • Thiago Pimentel

    I wanted to have a larger view of the values “y” and “speed” assume over time to have a better understanding of the gravity simulation and managed to add some lines of code in order to get an output. At first, I put a “println(“y: ” + y + ” speed: ” + speed);” at the end of the sketch but I thought it was not enough since the output from the console only shows a few lines of these values after the sketch is stopped. For my surprise, I was glad to realize that I anticipated what is covered at the chapter on debugging! So I thought it would be better to get a text file with the values without the space constraints of the console. I only had the slightest idea on how to do that since my previous programming experience was very narrow and at this point of the book anything related to this problem wasn’t yet covered. I struggled to find out a solution and skipped some chapters in hopes of discovering how to get this done. Moving back and forth throughout the book I stuck with a few pages from the chapters on arrays and strings, and with the help of the Processing reference, I came up with the following solution:

    >pre<
    float x = 100;
    float y = 0;

    float speed = 0;
    float gravity = 0.1;

    int i = 0;

    String[] sy = new String[4000];
    String[] sspeed = new String[4000];
    String[] values = new String[4000];

    void setup() {
    size(200, 200);
    for (int i = 0; i height) {
    speed = speed * -0.95;
    }

    sy[i] = str(y);
    sspeed[i] = str(speed);
    values[i] = “y: ” + sy[i] + ” speed: ” + sspeed[i];
    i = i + 1;
    if (i == 3000) {
    saveStrings(“values.txt”, values);
    }
    }
    >/pre<

    If you are going to give this code a shot, I recommend you to keep the sketch folder open and wait a little until the file “values.txt” appears, and then, you are free to stop the sketch. Undoubtedly this is not the most elegant solution, but it worked fine for me. Hopefully it will be helpful for those who may be curious on how these values change and it may serve as an alternative suggestion to help debug your codes (and it’s my very hope that Mr. Shiffman incorporates my humble solution in future editions of the book).

    One important thing is worth of notice here: although professor Shiffman recommends us to read the book in a linear fashion until, at least, the end of chapter 9 (and it has been a delightful read thus far =), it’s important to keep in mind that sometimes a more flexible approach urges the necessity to be used in conjunction (not substitute) with the more traditional and gradual path. By the way, I will continue to study this book without skipping any word.

  • Thiago Pimentel

    I wanted to have a larger view of the values “y” and “speed” assume over time to have a better understanding of the gravity simulation and managed to add some lines of code in order to get an output. At first, I put a “println(“y: ” + y + ” speed: ” + speed);” at the end of the sketch but I thought it was not enough since the output from the console only shows a few lines of these values after the sketch is stopped. For my surprise, I was glad to realize that I anticipated what is covered at the chapter on debugging! So I thought it would be better to get a text file with the values without the space constraints of the console. I only had the slightest idea on how to do that since my previous programming experience was very narrow and at this point of the book anything related to this problem wasn’t yet covered. I struggled to find out a solution and skipped some chapters in hopes of discovering how to get this done. Moving back and forth throughout the book I stuck with a few pages from the chapters on arrays and strings, and with the help of the Processing reference, I came up with the following solution:

    float x = 100;
    float y = 0;
    
    float speed = 0;
    float gravity = 0.1;
    
    int i = 0;
    
    String[] sy = new String[4000];
    String[] sspeed = new String[4000];
    String[] values = new String[4000];
    
    void setup() {
    size(200, 200);
    for (int i = 0; i height) {
    speed = speed * -0.95;
    }
    
    sy[i] = str(y);
    sspeed[i] = str(speed);
    values[i] = “y: ” + sy[i] + ” speed: ” + sspeed[i];
    i = i + 1;
    if (i == 3000) {
    saveStrings(“values.txt”, values);
    }
    }
    

    If you are going to give this code a shot, I recommend you to keep the sketch folder open and wait a little until the file “values.txt” appears, and then, you are free to stop the sketch. Undoubtedly this is not the most elegant solution, but it worked fine for me. Hopefully it will be helpful for those who may be curious on how these values change and it may serve as an alternative suggestion to help debug your codes (and it’s my very hope that Mr. Shiffman incorporates my humble solution in future editions of the book).

    One important thing is worth of notice here: although professor Shiffman recommends us to read the book in a linear fashion until, at least, the end of chapter 9 (and it has been a delightful read thus far =), it’s important to keep in mind that sometimes a more flexible approach urges the necessity to be used in conjunction (not substitute) with the more traditional and gradual path. By the way, I will continue to study this book without skipping any word.

  • Shashank

    I have put
    constrain(y,0,200); before if loop
    according to which it should not enter the if loop at all but y is still crossing the value 200…..i can’t understand why?
    Sorry, if its a stupid question though.

  • http://www.learningprocessing.com Daniel Shiffman

    constrain does not actually constrain the variable itself, it returns a result that is constrained. So you’d have to say:

    y = constrain(y,0,200);

  • Jim

    I think this very simple adaption using only a couple more lines gives a much more realistic simulation and solves the problems with oscillation and falling through the base:

    // Learning Processing
    // Daniel Shiffman
    // http://www.learningprocessing.com
    
    // Example 5-9: Simple Gravity
    
    float x = 100;   // x location of square
    float y = 0;     // y location of square
    float x2 = -0.75;
    float speed = 0;   // speed of square
    
    // A new variable, for gravity (i.e. acceleration).   
    // We use a relatively small number (0.1) because this accelerations accumulates over time, increasing the speed.   
    // Try changing this number to 2.0 and see what happens.
    float gravity = 0.01;  
    
    void setup() {
      size(200,200);
    
    }
    
    void draw() {
      background(255);
    
      // Display the square
      fill(175);
      stroke(0);
      rectMode(CENTER);
      rect(x,y,10,10);
      
      // Add speed to location.
      y = y + speed;
      
      // Add gravity to speed.
      speed = speed + gravity;
      
      // If square reaches the bottom
      // Reverse speed
      if (y > height-5) {
        // Multiplying by -0.95 instead of -1 slows the square down each time it bounces (by decreasing speed).  
        // This is known as a "dampening" effect and is a more realistic simulation of the real world (without it, a ball would bounce forever).
        speed = speed * x2 ;
      
      x2 = x2+0.01* gravity;
     y = height-5;  
        
      }
    
      
    }
    
  • squiva

    Did not work :(

  • Mag

    Good morning!
    I am searching for an easy way to stop the square in the destined location. I would like a series of falling squares to create a simple drawing…even without bouncing.
    I am a total beginner in Processing.
    Thank you for your help.

  • Programming-beginner

    Hi! If I wanted to make a ball bounce around on screen, how would I make the x-speed slow down with time, too? The y-acceleration works perfectly.

  • shiffman

    you’ll need to have separate xspeed and yspeed variables (in addition to variables for acceleration). you can use some dampening math to simulate friction.

    xspeed = xspeed * 0.95;

  • Ibrahim

    I didn’t understand the reasoning for the number -0.95, but -1 not working. With -1, it kept bouncing, but -0.95 had a “dampening” effect. I didn’t understand why -0.95 will have, but -1 did not. Anyone care to explain? Cheers!

  • Ibrahim

    I know -1 reverses the speed. But -0.95 will shave off 5% of the speed each time it bounces. So why doesn’t it come to a halt at some point? It keeps bouncing, which I don’t comprehend.