Coding a simple game jump

Hello you all, I need your help. So, recently i’ve been trying to challenge myself by designing a simple game with a red ball that can jump up and down and avoid obstacles. I plan to add the obstacles later, I’m just trying to get the “physics” down first. The problem is though, whenever I press ‘w’ for the ball to jump it just soars into the sky until I stop pressing the key, where then it falls in a straight down. I’ve tried over and over again but still cannot figure out how to make it jump once, and then fall back down (take for example Mario). Here is my code. If anyone has any solutions or possible ways to figure this out I would be extremely thankful. Have a nice day.

Code:
int X = 250;
int Y =200;
color up;
color down;
color left;
color right;
boolean w = false;
boolean a = false;
boolean d = false;
void setup() {
size(500,400);
noStroke();
}

void draw() {
background(255);
//Draws Plataform
fill(50,255,20);
rect(0,350,500,400);
//Ball
//Draws Ball
fill(255,20,50);
ellipse(X,Y,30,30);
//Makes Ball Fall
down = get(X,Y+15);
if(down != color(50,255,20) ) {
Y = Y+6;
}
//Creates border on World
if(X <= 15) {
X+= 5;
}
if(X >= 485) {
X-= 5;
}
//Checks for Jump
if(w && !a && !d) {
Y-=15;
}
//Checks for Veritcal Jumping
if(w && a && !d) {
Y-=15;
X-=5;
}
if(w && d && !a) {
Y-=15;
X+=5;
}
//Checks for Left
if(a && !d && !w) {
X-=5;
}
//Checks for Right
if(d && !a && !w) {
X+=5;
}
}
//sees which keys are being pressed
void keyPressed() {
if(key == ‘w’) {
w = true;
}
if(key == ‘a’) {
a = true;
}
if(key == ‘d’) {
d = true;
}
}
//Sees which keys are being released
void keyReleased() {
if(key == ‘w’) {
w = false;
}
if(key == ‘a’) {
a = false;
}
if(key == ‘d’) {
d = false;
}
}

You might try looking at this example of a jumping dinosaur I wrote a while back:

1 Like
1 Like

My version is less mean.

if you know some physics, you’ll know that Y = Yo + Vo * t + 1/2 * A * t**2 (the final t is squeared) so, if you set your gravity aceleration and an initial speed (Vo) and an initial position (Yo) you’ll get the final position (Y) in the Y axis, t will be the time between the moment that you press the “w” and the current time (something like: (millis() - momentOfJump))

Shameless self-promotion: here is a guide on collision detection, including handling games where the player must collide with the ground: