Skip to content

Instantly share code, notes, and snippets.

@pzp1997
Created February 25, 2015 17:45
Show Gist options
  • Save pzp1997/7e958a4bfdb0b9962f84 to your computer and use it in GitHub Desktop.
Save pzp1997/7e958a4bfdb0b9962f84 to your computer and use it in GitHub Desktop.
Gravity example by Stephen Lewis.
// gravity is simulated by increasing the downward velocity
// in the void draw() {}
float x, y, wid, ht;
float dy; // downward speed
float gravity; // strength of gravity's pull
float damping; // factor for how much energy the ball loses
// when it hits the floor
float upThrust; // upward force by user, if desired
float dx; // for left and right movement if you want
void setup() {
size (500,500);
x=100;
y=100;
wid = 50;
ht = 50;
dx = 5; // optional left and right movement
// if you don't want any x movement, set dx to 0 or remove this variable
dy = 3; // starting value of downward speed
// good gameplay values might require that you balance
// all three of these values:
gravity = .5; // you can choose this value so it's realistic
damping = -.7; // you can choose this so it's realistic
upThrust = -2; // // you can choose this value so it's realistic
}
void draw() {
background(127);
dy += gravity; // increase downward speed
y = y + dy; // move the ball downward
ellipse (x, y, wid, ht);
// if you want the ball to bounce
// off the floor use this code
// the damping factor is there to diminish the bounce
// because a bouncing ball loses energy when it hits the floor
if (y > height) {
y = height; // if it's past the floor put it back at the floor level
dy = dy * damping; // damp its speed because it loses some energy on bounce
}
// if you want the user to be able to give the ball
// some upward energy on a mouse click or keypress
if (keyPressed) {
dy += upThrust; // note it's a negative number because it pushes "up"
}
// you can also have the ball moving left and right
x += dx;
if (x > width) {
x = width;
dx *= -1;
}
if (x < 0) {
x = 0;
dx *= -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment