// Example 5-9: Simple Gravity
float x = 00; // x location of square
float y = 0; // y location of square
float speed = 0; // speed of square
int xspeed=5; //speed going across
// 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 = 1.0;
void setup() {
size(1280,1000);
}
void draw() {
background(255);
println("x is " + x);
println("xspeed is " + xspeed);
println("y= " +y);
println("speed is " + speed);
println();
// Display the image
PImage b;
b = loadImage("mad_200.jpg");
image(b, x, y);
if (x>width-100 || x<0)
{
xspeed=xspeed*-1;
}
x=x+xspeed;
y=y+speed;
// Add gravity to speed.
speed = speed + gravity;
// If square reaches the bottom
// Reverse speed
if (y > height-200) {
// 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;
}
}