This programming of gravity that I am about to show you is probably not the best in the world. It is probably one of the worst. But here I go…
(Any of the code could be messy, not needed or could be done a better way)
Let’s talk about gravity first. Gravity is a force that keeps us stuck to Earth. Many things, like gyroscopes, would not work without gravity. We wouldn’t even be here talking if it wasn’t for gravity. Gravity is very hard to escape. Gravity also builds up as you fall down, so you go faster as you fall down longer. Unless you are making some sort of space game, gravity is an absolute must.
[h1]Gravity[/h1]
So, first you will have to make something to check if you have ground beneath you. I don’t care how you do it. Then you need to make something to keep that result.
(There are probably many, many, ways to check)
boolean isSupported;
boolean isGround;
You may be wondering why there is a variable called isGround. This means that there is ground beneath your character. isSupported means that if there is something directly beneath your character.
Now you need some more variables. These are:
final int gravity = 20;
int gravitypull = 1;
boolean isRunning = true;
int jumpingPower = 4;
boolean jumping = false;
int height = 0;
Then you need something to check to see if there is ground below you and if you are jumping.
public void gravityEffect(){
if (!isSupported){
if (jumping){
if ((gravity / 2) == height){
jumpingPower /= 2;
}else if ((gravity /4) == height){
jumpingPower /= 4;
}
height += jumpingPower;
System.out.println(height);
}else if (!isGround | height >= gravity){
height -= gravitypull;
jumping = false;
System.out.println(height);
gravitypull *= 2;
}
}
}
It stops you if your height reaches the gravity’s limit.
Finally, you need something to stop you when you are at ground. (I have put 0 in, but you will have to put in the number where the bottom of the ground is)
if (isGround & height <= 0){
height = 0;
gravitypull = 1;
isSupported = true;
}
It’s as simple as that! ;D