How to make an event starts working when a key is pressed?

edited April 2015 in How To...

I'm a beginner I'm using processing to build a small game. I am trying to make the character in the game jump up to the air and then fall down from the air to the ground slowly when the keycode "UP" is pressed. Following is some parts of what I wrote:

PImage jumpingPlayer=new PImage[20];
PImage gridJumpingPlayer=loadImage("jumping.png");
//facing to the right
for (int i=0; i<20; i++) {
  jumpingPlayer_r[i]=gridJumpingPlayer.get(i*500, 0, 500, 1500);
}

//time
t=0;
if (keyPressed==true) {
  if (key==CODED) {
    if (keyCode==UP) {
      //When "UP" is pressed, the player character is jumping up.
      t+=1;
      image(jumpingPlayer_r[t%jumpingPlayer_r.length], x, y, 150, 500);
    }
  } else {
    //When no key is pressed, the player is standing on the ground.
    t=0;
    image(standingPlayer, x, y, 150, 150);
  }
}

So my problem is that this whole jumping process (jumping up to the air and then falling down from the air to the ground) works only when I keep pressing the key "UP" and not releasing the key.

Once I release the key "UP", even if the character just jump up and is still in the air, it will skip the process of falling and stand on the ground immediately.

I am wondering whether it is possible to make the whole jumping process work once the key is pressed. Or is ti possible to make like follwing?

if(keyCode==UP){
  something starts working...
}

Hope that I explained my problem well... Any help would be really appreciated!jumping player副本

Answers

  • Answer ✓
    int h = 0;
    
    void setup(){
      size(220,220);
      rectMode(CENTER);
    }
    
    void draw(){
      background(0);
      translate(110,110);
      stroke(0,255,0);
      noFill();
      if(h>0)h--;
      rect(0,abs(h-50),20,20);
    }
    
    void keyPressed(){
      if(h==0)h=100;
    }
    
  • Answer ✓

    As said (implied) by TfGuy44, use the keyPressed() callback to trigger the jump once, and set a variable telling a jump is going on.

  • Thank you, TfGuy44 and PhiLho! You guys really helped me a lot! Now my program works as I expected :)

Sign In or Register to comment.