Moving a player rectangle smoothly

Hello! I like making simple arcade-like games in processing and have always had an issue with smooth movement.

At first, I was using the void keyPressed() function to move the player.

void keyPressed()//keypressed fuction is called when any key is pressed down, and continutes being called until all keys are released
{
     if(key == CODED)//for arrow keys, enter, etc.
     {
            if(keyCode == DOWN) playerY += speed//update the player's coordinate integer so that the player moves on the screen(inside my rect(x, y, w, h) in void draw)
      }
}

The code above would move the player one frame, then pause a second, then continue.

I then realized it was better to do this:

void draw()
{
if(keyPressed)
  {
    if(key == 'w') playerY -= playerSpeed;
    if(key == 's') playerY += playerSpeed;
    if(key == 'a') playerX -= playerSpeed;
    if(key == 'd') playerX += playerSpeed;
  }
  fill(30, 200, 30);
  rect(playerX, playerY, playerWidth, playerHeight);
}

By checking the keys directly inside of draw, the 1 second pause was eradicated. However, I still have some issues with this code.

If I hold down a vertical key then hold down a horizontal key at the same time, let’s say ‘a’ and ‘w.’ instead of moving diagonally - in this case up and to the left - the player will move left at first(when I start off by holding just ‘a’) but as soon as I hold down ‘w’ as well, it stops going left and only goes up. To make things worse, if I then let go of ‘w’ so that ‘a’ is the only key being pressed, the player will keep moving up until I let go of ‘a.’

That issue exists for any combinations of keys, vertical or horizontal, or even if I, for example, start off with up, then go down, let go of down, it keeps going that way.

Please help. Once I get this figured out I have a more specific problem for a new game I am trying, but I want to fix this nasty movement first.

void keyPressed(){
  k(true);
}

void keyReleased(){
  k(false);
}
 
int[] ks = {'a','s','d','w'};
boolean[] kd = {false, false, false, false};
 
void k(boolean b){
 for( int i = 0; i < ks.length; i++){
   if( ks[i] == keyCode ) kd[i] = b;
 }
}

Now you will have an array, kd, which tracks which keys of interest are being held down. You can use the values in that array to move your player rectangle based on some conditional statement.

1 Like

Hi @Edgard142ofWelshdale
To go diagonal you have to use something like

if(key == 'd'){
      playerX += playerSpeed;
      playerY += playerSpeed;
    }
1 Like

You can search on google “processing smooth character movement” to find more similar posts.
The code in this post worked great for me.

1 Like