This code example shows how to handle keyboard events. Press the A, B or C keys and see the output in the chat window. The keyboard listener checks for all keybaord activity with onEvent(), key presses with onKeyDown() and key releases with onKeyUp(). All the code and assets are in the projects Scripts directory. You can download the project using the link above.
// Turn on debug so that Chat.printDebug() and Chat.dump() work
Chat.debugOutput = true;
// Display the stats panel in the bottom left corner of screen
Application.statsVisible = true;
// Turn on collisions, but allow the user to turn it off
Actor.setCollisionSetting( true, false );
// Turn on gravity, but allow the user to turn it off
Actor.setGravitySetting( true, false );
// Show the chat panel
Application.chatPaneVisible = true;
// Set ambient light for the scene
Scene.ambientLightColor = Color(0.5, 0.5, 0.5, 0);
// Create a point light
var oPointLight = Scene.createPointLight( "SceneLight" );
oPointLight.position = Vector( 0, 600, -500 );
// Create a Skydome
var oSkyDome = Scene.createSkyDome();
oSkyDome.materialName = "CloudySky";
oSkyDome.curvature = 5;
oSkyDome.tiling = 8;
oSkyDome.distance = 4000;
oSkyDome.enable = true;
// Create the floor
var oGround = Scene.createGround( "MainFloor", "RustySteel", 3000.0, 3000.0, true );
Chat.print( "Press the A, B or C keys" );
// Create the keyboard listener
this.oKeyListener = new Object();
this.oKeyListener.bKeyBPressed = false;
this.oKeyListener.onKeyDown = function()
{
// Check for key presses
if ( Key.isKeyDown( Key.KEY_A ) )
Chat.print( "onKeyDown: Key A was pressed" );
if ( Key.isKeyDown( Key.KEY_B ) )
{
this.bKeyBPressed = true;
Chat.print( "onKeyDown: Key B was pressed" );
}
}
this.oKeyListener.onKeyUp = function()
{
// Check to see B key was previously pressed and has now been released
if ( this.bKeyBPressed && !Key.isKeyDown( Key.KEY_B ) )
{
this.bKeyBPressed = false;
Chat.print( "onKeyUp: Key B was released" );
}
}
this.oKeyListener.onEvent = function()
{
if ( Key.isKeyDown( Key.KEY_C ) )
Chat.print( "onEvent: Key C was pressed" );
}
// Add the key listener
Key.addListener( this.oKeyListener );