Trying to create a jumping character

I’m trying to create a character that jumps when ever i press the up arrow.

let r = 20;
let x = 200;
let y = 380;
let speed = 8;
let gravity = 0.2;

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

function draw() {
  background(220);
  player();


}

function player() {
    ellipse(x, y, r*2);
  if(keyCode === UP_ARROW) {
    speed -= gravity
    y -= speed;
  }
  if(y > height - r) {
		speed = 0;
    y = 380;
  }
}

this is my code right now, but i can’t get the character to stop moving after its reached the bottom of the screen. If anyone could help me, that would be very useful, thanks

1 Like

Nice work, almost there.

at the start of the program, what is the value of speed? and what is it after you land your jump?
you can explore this by adding print(speed); to the draw() function.
the speed should probably be reset to 8 if the last key pressed was not the up arrow.

Changing this might lead to other unintended consequences (like being able to chain jumps). Because (keyCode===UP_ARROW) doesn’t execute when the up key is pressed, it executes many times while the up arrow was the last key pressed. Later, you might want to make it so you can’t jump if you are already jumping, or to place the (keycode===UP_ARROW) code into a keyPressed() function so it executes only once.

1 Like

Thank you, this was really helpful.