Hi, so Iām trying to move a square around the screen using the arrow keys. I have the code written for the square to move right when the right arrow key is pressed, but the square keeps moving once the key is released. How do I make the square stop once the right arrow key is released?
Thanks in advance
float x, y;
void setup() {
size(600, 600);
noStroke();
x = width/2;
y = height/2;
}
void draw() {
background(0);
rect(x, y, 20, 20);
if (key == CODED) {
if (keyCode == RIGHT) {
x = x + 1;
}
}
}
1 Like
There are built-in methods which called when the key is pressed or released
https://processing.org/reference/keyPressed_.html
https://processing.org/reference/keyReleased_.html
add these method to your code to override the built-in methods
you can use these to handle the situation, something like thiz
void keyPressed(){
if(key == CODED){
if(keyCode == RIGHT){
moving();
}
}
}
void keyReleased(){
if(key == CODED){
if(keyCode == RIGHT){
stopMoving();
}
}
}
if you bother to use these methods, another way is to use global variable named keyPressed
(boolean) which tell if any key being pressed, just modify the code lil bit
if(keyPressed){
if (key == CODED) {
if (keyCode == RIGHT) {
x = x + 1;
}
}
}
2 Likes
Thanks very much @humayung !