keyDown()

Category:Game Lab

Checks if the key specified is pressed.

Some interactive games use the keyboard for the user input to control the game.

Examples

function draw() {
  console.log(keyDown("up"));
}

Driving

Drive a square using the UP DOWN LEFT RIGHT keys.

// Drive a square using the UP DOWN LEFT RIGHT keys.
var sprite = createSprite(200, 200);
function draw() {
  background("white");
  if (keyDown("up")) {
    sprite.y=sprite.y-1;
  }
  if (keyDown("down")) {
    sprite.y=sprite.y+1;
  }
  if (keyDown("left")) {
    sprite.x=sprite.x-1;
  }
  if (keyDown("right")) {
    sprite.x=sprite.x+1;
  }  
  drawSprites();
}

Rotary Phone

A rotary phone dialer controlled by the keys 0 through 9.

// A rotary phone dialer controlled by the keys 0 through 9.
var dial = createSprite(200, 200);
dial.setAnimation("dial");
var peg = createSprite(285, 265);
peg.setAnimation("peg");
var target=0;
function draw() {
  background("white");
  if (keyDown("1")) target = 25;    
  else if (keyDown("2")) target = 57;
  else if (keyDown("3")) target = 89;
  else if (keyDown("4")) target = 121;
  else if (keyDown("5")) target = 153;
  else if (keyDown("6")) target = 185;
  else if (keyDown("7")) target = 217;
  else if (keyDown("8")) target = 249;
  else if (keyDown("9")) target = 281;
  else if (keyDown("0")) target = 313;
  else target = 0;
  if (dial.rotation<target) {
    dial.rotation=dial.rotation+5;
  }
  if (target==0 && dial.rotation>0) {
    dial.rotation=dial.rotation-5;
  }  
  drawSprites();
}

Syntax

keyDown(code)

Parameters

NameTypeRequired?Description
code String The name of key you want to check. Keys without a letter or number have names like "up", "left", "shift", "tab", "space", etc.

Returns

Boolean true or false.

Tips

  • When testing your games that use keyboard or mouse input make sure you click in the display area before you run, otherwise the Workspace will record your keyboard and mouse actions.

Found a bug in the documentation? Let us know at documentation@code.org