Processing program-Simple Gravity

Our workshop on programming in the Processing computer language is this coming Sunday Dec 8. I'm looking forward to seeing you then!  

Would you like to get started with Processing before the workshop? Here's a simple program I've written (based on one in "Learning Processing" by Shiffman) that illustrates something I'm sure you'll recognize and which you are welcome to use as you wish, whether or not you attend the workshop. You can run and modify it as you like. I've put comments in the program (after the "//" symbols) explaining how it works. The actual program code is below, so you can see what it looks like and review my comments, which I hope are helpful.

To run the program, you must have downloaded and installed Processing, following the instructions at <http://Processing.org/tutorials/gettingstarted/>. 

You should save the attached file ("SIMPLE_GRAVITY.pde") in a known location on your hard drive. When you click on the file, Processing will start and will ask you if the file can be moved to a folder named "SIMPLE_GRAVITY". Click "yes," and the program code will appear in the Processing window. Click the play button at the top of the window to run the program. Please let me know what you think!

Fernand Brunschwig, Chairman
STEMteachersNYC (formerly PhysicsTeachersNYC)
===============
/* Initialize variables - origin is at top left of window; 
x positive to right, BUT Y IS POSITIVE DOWN.*/
float x = 0; // Floating point (decimal) number is initial horizontal position
float y = 0; // Floating point (decimal) number is initial vertical position
float xspeed = .5; // Initial horizontal speed (constant)
float yspeed = 0; // Initial vertical speed
float yacceleration = 0.04; // Vertical acceleration (constant, down)

// Setup size of window
void setup() {
  size(400,400);
}

// Draw function which repeatedly redraws window by running commands below it
void draw() { 
  background(255); // White background
  ellipseMode(CENTER); // Position of ball measured from center
  fill(0); // Inside of ball is black
  ellipse(x, y, 20, 20); // Draws ball with center at {x,y}, width & height=20 pixels
  x = x + xspeed; // Horizontal position of ball increases by constant amount each time window is redrawn
  y = y + yspeed; // Vertical position of ball increases each time window is redrawn
  yspeed = yspeed + yacceleration; // Size of increment of vertical position increases at each redrawing

/* If ball hits bottom of window, reverse direction of 
vertical speed so ball bounces up with 95% of previous speed (damping).*/
  if (y > height) {  
    yspeed = yspeed * -0.95;
  }  //end of "if" function

/* If ball hits either side of window, reverse direction of 
horizontal speed so ball bounces back with 100% of previous speed.*/
  if (x > width || x < 0) {
    xspeed = xspeed * -1;
   }  // End of "if" function
} // End of commands run by "draw" function
ċ
SIMPLE_GRAVITY.pde
(2k)
Leah Segal,
Dec 1, 2013, 1:23 PM
Comments