How to connect my code with the key pressed event and what should I do to make my character jump? (Duplicate thread)

I have been coding a simple game and I’m stuck in the key pressed events and my intention is to make my character move backwards, onwards, upwards and downwards. Where should I place the keypressed code to connect it with the character? And the jumping part of my code should be inside the key pressed code? Please, excuse my lack of knowledge towards Processing once I have been studying it for just a few weeks.

My code:


// images
PImage background;

// bee character
float charSpeed = 5.5;
float charX, charY;
PImage[] charImage= new PImage[4];
int px, pf;

public void setup() {
  size(800, 600); 
  noFill(); // to adjust the image in the screen properly in fullscreen
  background = loadImage("YellowFlowers.jpg"); 
  background.resize(width, height); 

  // load bee

  charImage[0] = loadImage("bee walk 1.png");
  charImage[1] = loadImage("bee walk 2.png");
  charImage[2] = loadImage("bee walk 3.png");
  charImage[3] = loadImage("bee walk 4.png");
}  


// ******* drawing section ! *********** //

// background draw
public void draw() {
  image(background, 0, 0); 

  //bee character

  image(charImage[pf], px, 0);
  if (++pf > 3) pf = 0;
}




Place the keyPressed code in draw()

See reference

For jumping you set a negative value addY that you add to y (rising) and increase addY until it’s +2 or so

When player hits the ground say addY=0;

Or something like this

1 Like

Hi! Thanks for answering my questions. I have already coded the key pressed part and it works nicely, but I still need guidance when it comes to where I should place the jumping code. Should I write it inside Keypressed() alongside with the code for moves?

1 Like

No, everything inside if(Keypressed) or function Keypressed() does only run as long as the key is hold / or once.

therefore please set the variable addY here.

The usage of addY must take place in the main part and not inside if(Keypressed) or function Keypressed()

1 Like

Let’s continue in your other thread