How to Detect a Key Press in Processing

This Sketch shows you how to detect a key pressed. Note that in the draw function there is no code for the key. The function “public void keyPressed()” is automatically called when a key is detected. It then stores the key in two variables. key which stores the key character – and keyCode which stores the number. If you want to detect an arrow key use the keyCode variable. See the main functins on how this works.

Great for games that need a keypress


// Simple sketch to show key pressed
int ballx=0;
int bally=0;
int speed=10;

public void setup()
{
    size(600, 600);
    background(0);
}

void draw()
{
  smooth(); 
  background(0);
  ellipse(ballx,bally,20,20);   
}

public void keyPressed()
{
  
    println("Key code pressed: " + keyCode);
    
    if (key == 'w')
    {
      ballUp();
    }
    else if (key == 'z')
    {
        ballDown();
    }
    else if (key == 'a')
    {
        ballLeft();
    }
    else if (key == 's')
    {
        ballRight();
    }
        
}
public void keyReleased()
{
    println("Just to let you know a key has been released");
}

void ballUp()
{
  if ( bally >=0 && bally <= width )
  {
    bally = bally-speed;
  }
}

void ballRight()
{
  if ( ballx >=0 && ballx <= width )
  {
    ballx = ballx+speed;    
  }
}

void ballLeft()
{
  if ( ballx >=0 && ballx <= width )
  {
    ballx = ballx-speed;   
  }
}
void ballDown()
{  
  if ( bally >=0 && bally <= height )
  {
    bally = bally+speed;   
  }
}
Advertisements

2 comments

    1. You can use a ascii code comparison as the number say 34 for ” or 39 for ‘ or just use the \ char to escape it like this

      else if (key == ‘\”)

      the ascii version is else if (key == 222)

      when you hit a key it shows you the numeric value so you can try that

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s