Keyboard Component

Provides entity with keyboard events.

Events

KeyDown [Crafty's KeyboardEvent = { key: `Crafty.keys` keyCode (Number), originalEvent: original KeyboardEvent }]
is triggered for each entity when the DOM 'keydown' event is triggered.
KeyUp [Crafty's KeyboardEvent = { key: `Crafty.keys` keyCode (Number), originalEvent: original KeyboardEvent }]
is triggered for each entity when the DOM 'keyup' event is triggered.

In addition to binding to these events, the current state (pressed/released) of a key can also be queried using the .isDown method.

Example

Crafty.e("2D, DOM, Color, Keyboard")
  .attr({x: 100, y: 100, w: 50, h: 50})
  .color("red")
  .bind('KeyDown', function(e) {
    if (e.key == Crafty.keys.LEFT_ARROW) {
      this.x = this.x-1;
    } else if (e.key == Crafty.keys.RIGHT_ARROW) {
      this.x = this.x+1;
    } else if (e.key == Crafty.keys.UP_ARROW) {
      this.y = this.y-1;
    } else if (e.key == Crafty.keys.DOWN_ARROW) {
      this.y = this.y+1;
    }
  });

Methods

Back to top

.isDown()

public Boolean isDown(String keyName)
keyName

Name of the key to check. See Crafty.keys.

public Boolean isDown(Number keyCode)
keyCode

Key code in Crafty.keys.

Determine if a certain key is currently down.

Example

ent.requires('Keyboard')
   .bind('EnterFrame', function() {
      if (this.isDown('SPACE'))
         this.y--;
   });

See Also