Gravity

Avi Gupta
hackerLog
Published in
3 min readJan 20, 2019

So we all know what gravity is.

If you don’t, you probably weren’t paying attention in school. Well, gravity is the force that keeps us down on earth.

But what I haven’t done is simulate it.

Until now!

This it what it looks like:

What the program will do. (Just a shorter gif of it)

So, how did I write the code for this one?

First, we declare our universal variables:

// gravity program...!float x, y, r; 
float speed, gravity = 0.1, xc;// declares changes in location
float h;// for color...

Then, we set up the stage for the ball using void setup().

// set up program
void setup() {
size(600, 600);
ellipseMode(CENTER);

// helps create rainbow effect
colorMode(HSB, 360, 100, 100);
background(0, 0, (100/255) * 20);
frameRate(100);
// init. variables
x = width/2;
y = 0;
r = 20;
xc = 1.5;
h = 0;
}

After that, we draw out the circle using void draw.

// draws it out
void draw() {
background(20);
fill(h, 100, 100);
noStroke();
ellipse(x, y, r*2, r*2);

That’s not the end of it. speed changes the y at a certain rate, which helps to simulate gravity.

// change y
y = y + speed;

Now, you may be thinking: “won’t that cause it to fall at a constant speed?
No. Because gravity puts a change on the speed.

// increases the change of y
speed = speed + gravity;

Also, we add the bounce factor:

if(y > height - r){
// by 0.99 so that the jump peak goes down slightly every bounce
speed = speed * -0.99;
}

This changes the y variable so that the ball goes down and bounces like it has the effects of gravity.

The change in the x variable is a little different:

// change x
x = x + xc;

// || means OR. We use OR because that way, we can set it to either edge.
if(x > width - r || x < r){
xc = xc*-1;
}

Now, about the variable h. That wasn’t just a variable just lying around there. It is used to create the rainbow effect in the color of the ball.

// increases the hue and makes it go back from the highest hue to the lowest
// which are the same color (RED)
h++;
if(h > 360){
h = 0;
}
}

Which makes the ball have a rainbow pattern in its colors, since the hue is always increasing by 1.

So that’s how we made the gravity and the rainbow effect on the ball… yeah!

Play around with the change in speed or the gravity to affect the gravitational force and the “bounciness” of the ball. Gravity is an interesting thing, and simulating it is kind of hard to do.

This program simulates only one ball. Next time, we’ll do an object oriented code that will simulate multiple balls.

See the full code on GitHub here.

Signing out ‘till next time,

Avi.

--

--

Avi Gupta
hackerLog

Named after the first 2 games I got on my xBox, Forza and Minecraft. Also, i have a blog. Real name is Avi.