How to make gravity when you jump

:l idk i don’t know

First, a little bit of physics: What gravity does is accelerate you downwards, which means your downwards speed increases every moment. So in order to code this you need to keep track of not just the position of your character, but also their speed.

The way I usually do this is with this.speed_x, and this.speed_y.

So you have your character in a clip, then on the Default script you start out with no speed:
this.speed_x = 0;
this.speed_y = 0;

Then on update, you change the speed according to gravity:
this.speed_y += 3;

And update the location:
this.x += this.speed_x;
this.y += this.speed_y;

I also like to add some friction so the character can’t just keep accelerating:
this.speed_x *= 0.9;

And you also need to make it so the player doesn’t just fall through the ground:
if (this.y > 480) {
this.y = 480;
this.speed_y = 0;
}

Finally, you need some controls:
if (isKeyDown(“left”)) {
this.speed_x -= 3;
}
if (isKeyDown(“right”)) {
this.speed_x += 3;
}

Also in the Keypressed script (for jumping):
if (key === “up”) {
this.speed_y -= 30;
}

Here’s an example project, let me know if you have any questions! Right now, the character can keep jumping in the air whether or not they are touching the ground, can you add some code to the Keypressed script so that they can only jump if they’re on the ground?
GravityJump7-8-2020_11-59-51AM.wick (10.3 KB)

2 Likes

thanks you

2 Likes

i did the gravity code and it worked but i have barriers that would block a player from going through with just moving around but now when the player is falling it just goes straight through the barrier.

Hi! To find out what I can do, say @discobot display help.

that has absolutely nothing to do with the conversation and this conversation is two months old why

4 Likes

Chase spencer, if you see this, try naming the hitboxes and changing this code (this.y > 480) {
this.y = 480;
this.speed_y = 0;
}

to whenever you collide with the hitbox to change the speed thing above to a different number if it’s for a platforms game or something of the sort

i am so sorry but i have figured it out by now sorry