How can I set a move while hold a key?

Hi everyone,

I made this little code and I want to hold the ‘d’ key to make the ball move to the right.

I want to move the ball until the edge of the screen just holding ‘d’ key. In the way that the code is, I need to press many times the button and I don’t want that. Please help me.

int x = 50;

void setup(){
size(100,600);
background(50);
}

void draw(){
background(50);
ellipse(x,y,24,24);
}

void keyPressed(){
 if(key == 'd'){
 x=x+2;
} 
}

have a boolean flag which is set when the key is pressed, and use said flag to determine whether or not you should be moving.

bPressed = false;

if(keyPressed & key = " someKey"){
bPressed= true;
}

if(!keyPressed){
bPressed = false;

}


if(bPressed) doSomething();
1 Like

Many thanks, but could you please put your example inside my code? I’m getting some errors here in the first line “bPressed = false;”. The error is: expecting EOF, found ‘bPressed’

My code isn’t meant to run, its meant as an example for the logic.

Booleans need to be declared first;

boolean a = false;

^ writing boolean before a variable name declares it as a boolean. This is the same for all other variable types.

instead of

if(key == 'd'){
x=x+2;
}

i think it should be

if(key == 'd'){
x+=2;
}
1 Like

Wonderful! Many thanks