Same jumpheight with changing gravity

Viewed 62

I am trying to recreate the google-chrome offline Dino game. In this game the Dino has a gravity-pull on himself and it has a jump velocity, an upwards speed applied when the user presses the space bar.

Over time the obstacles move faster and faster to the player. When the obstacles move faster the Dino's jump should also be faster.

I tried to make a faster jump by increasing the gravity over time, so the Dino gets pulled down faster. But how do I get the Dino to jump the same height, let's say, 50 pixels upwards, no matter what the gravity is.

I tried working with the formula's: y = 0.5*a*t^2 + v(0)*t But I can't come to a correct answer.

The canvas this code is working as regards the top left corner as the origin(0,0). Therefore the jump velocity is negative and the gravity is positive.

This code is inside the Dino class, where this references to the Dino. In the constructor of the Dino class I have the code

this.y = 0;
this.vy = 0;
this.gravity = 1;
this.speed = 0;

In the update function that is called each x amount of time:

this.speed += 0.001;
this.y += this.vy;
this.vy += this.gravity;
this.gravity += speed*0.001;

The jump function- executes when the spacebar is pressed:

this.vy = (-?);

The amount of pixels the dino jumps gets higher over time. How could I make the Dino jump the same amount of pixels every time no matter the gravity?

1 Answers

So I personally would do this a little differently. I would specify a maximum y; the highest point our object can jump. Then when the player hits the jump button, it will Linearly Interpolate to that position, this works perfectly for your problem as in p5 they've spoiled us with a lerp() function where you can specify the amount to lerp by, so the faster your game gets the quicker we want the player to jump so the higher we set the lerp.

To determine how fast we lerp I've used upSpeed which you will increment as the game progresses:

const MAX_Y = 150;
let y = 370;

let upSpeed = 0.1;

function setup() {
  createCanvas(400, 400);
  
}

function draw() {
  background(220);
  
  fill(255, 100, 100);
  
  y = lerp(y, MAX_Y, upSpeed);
  ellipse(width / 2, y, 50, 50);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>

And then add your gravity magic to the equation and you've got yourself a game!

Related