How do I increase the speed of a rectangle whenever I press a key?

int X=20;
int Y=20;
int howBig=20;

void setup() {
size(700, 700);
background(196, 196, 196);
}

void draw() {
background(196, 196, 196);
rect(X, Y, howBig, howBig);
fill(113, 113, 113);
}

void keyPressed() {
background(196, 196, 196);
if (key == CODED) {
if (keyCode == UP) {
Y = Y-10;
} else if (keyCode == DOWN) {
Y = Y+ 10;
}
}

if (key == CODED) {
if (keyCode == RIGHT) {
X = X+10;
} else if (keyCode == LEFT) {
X = X-10;
}
}
}

First you need a way to store the speed.
Looking at your code, I would suggest to use an integer.

Give it a clear name like speed or something like that. Given that you have both X and Y positions, you need two variables.

set it to initial speed and modify it if the buttons are pressed.
replace the function of keys, to not change the position but the speed.

Lastly, you should update position with speed.
So something like:
xPos += xSpeed;
yPos += ySpeed

keep in mind, that the faster the update rate, the smoother the ‘animation’ looks. In programs like these, they are updated every frame. But if there are 60 frames per second, and speed is 1, it will move 60 pixels in a second. Try to play with the numbers to get your desired result.

Thank you so much for the help. How would I do this step? “set it to initial speed and modify it if the buttons are pressed.
replace the function of keys, to not change the position but the speed.”

1 Like

Something like this; Fill out the rest.

int Xspeed = 0;
int Yspeed = 0;

//all other code

void keyPressed() {
   //previous:
   //void keyPressed() {
   //   if(key == 'a') xpos -=10;
   //}
   //now:
   void keyPressed() {
      if(key == 'a') Xspeed-=1;
      if(key== 'w') Yspeed-=1;
   }
}