KeyboardState Component

Handles valid key related events and key states for the entity.

Note: This is an internally used component, automatically included in the KeyboardSystem.

Events

KeyDown [Data = {KeyboardEvent}]
when a key is pressed
KeyUp [Data = {KeyboardEvent}]
when a key is released

The standard Crafty KeyboardEvent object:

// event name of key event
e.eventName

// Normalized keyCode number according to `Crafty.keys`
e.key

// Original keyboard event, containing additional native properties
e.originalEvent

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

Methods

Back to top

.isKeyDown()

public Boolean isKeyDown(String keyName)
keyName

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

[Returns]

The pressed state of the key

public Boolean isKeyDown(Number keyCode)
keyCode

Key code in Crafty.keys.

[Returns]

The pressed state of the key

Determine if a certain key is currently down.

Example

ent.bind('UpdateFrame', function() {
  if (Crafty.s('Keyboard').isKeyDown('SPACE'))
    this.y--;
});
Back to top

.resetKeyDown()

public this .resetKeyDown()

Reset all currently pressed keys. Triggers appropriate "KeyUp" events.

This method is called internally, but may be useful when running Crafty in headless mode.

Back to top

.triggerKey()

public this triggerKey(String eventName, Object eventData)
eventName

Name of the key event to trigger ("KeyDown" or "KeyUp")

eventData

The key event to trigger

Try to trigger a key event on this entity and persist the key state. This method prevents inconsistent key state. e.g. If this entity didn't receive a "KeyDown" previously, it won't fire a "KeyUp" event.

This method is called internally, but may be useful when running Crafty in headless mode.

Example

var wasTriggered = false;

ent.requires('KeyboardState')
   .bind('KeyUp', function(evt) {
      wasTriggered = true;
   })
   .triggerKey('KeyUp', { key: Crafty.keys.RIGHT_ARROW });

Crafty.log(wasTriggered); // prints false

See Also