# Keyboard buttons

**URL:** https://discourse.processing.org/t/keyboard-buttons/717
**Category:** Coding Questions
**Created:** [June 5, 2018, 3:20am UTC](https://discourse.processing.org/t/keyboard-buttons/717 "2018-06-05T03:20:45Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![TfGuy44](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tfguy44/32/41_2.png) [@TfGuy44](https://discourse.processing.org/u/TfGuy44)
#### Post date: [June 5, 2018, 4:26am UTC](https://discourse.processing.org/t/keyboard-buttons/717/2 "2018-06-05T04:26:51Z")

</div>

I recently wrote some code that deals with tracking which keys are down in a neat way:

> [@Mario game help! Move background screen when image is moved?](https://discourse.processing.org/t/mario-game-help-move-background-screen-when-image-is-moved/659/4):
>
> No! You can certainly have a background image that is larger than your sketch! I took a bit of time to code you a working example: float background\_x\_offset; float mario\_x\_position; float mario\_y\_position; PImage bg; void setup(){ size(200,200); spoofBackgroundImage(); background\_x\_offset = 0; mario\_x\_position = width/2; } void draw(){ background(0); if( kd[0] ) mario\_x\_position--; if( kd[1] ) mario\_x\_position++; if( mario\_x\_position \> 3\*width/4 && background\_x\_offset \< 600 ){ …

Here’s the code that counts:

```auto
void keyPressed(){
  k(true);
}

void keyReleased(){
  k(false);
}
 
int[] ks = {LEFT, RIGHT};
boolean[] kd = {false,false};
 
void k(boolean b){
 for( int i = 0; i < ks.length; i++){
   if( ks[i] == keyCode ) kd[i] = b;
 }
}

```

Notice that this defines two arrays. `ks` is the keys that you wish to track. `kd` is a boolean array that records if the key in `ks` at the same index is held down.

You can use this in your conditional checks:

```
if( kd[0] && kd[1] ){ // If LEFT arrow and RIGHT arrow are held down at the same time.

```

Notice that this is using the logical AND operator, `&&`, not the addition operator `+`!

---

_[View the full topic](https://discourse.processing.org/t/keyboard-buttons/717)._
