Blog

Simulating TV Remotes in AS3

Simulating TV Remotes in AS3

A lot of the work we do involves building PC/Mac based demos of planned interactive TV services. The most common requirement when building these is to simulate the buttons found on a standard TV remote, using a computer keyboard (so R is mapped to the red button on the remote, Enter is mapped to the select/ok button on the remote, etc).

This isn’t a difficult task to accomplish using standard keyboard event handlers, but it’s not a particularly nice way to do it. Also, new mappings will often need to be added at a late stage in the project (e.g. mapping Space to select, in addition to Enter), or support will need to be added for soft key codes for a mobile demo, or any number of other complications. To streamline this process, we came up with the InputController class.

You can download the class here: InputController. Usage instructions are included in the class, and also below:

Usage

In order to make things as simple as possible, and to allow you to listen to the input controller from anywhere in your app, it is defined as a static class. You need to initialise the InputController class before using it, in order to pass it a reference to the stage. This just requires one line of code:

InputController.init(stage);

You can then listen for InputEvents from the InputController, in the same way as you would any other class:

InputController.addEventListener(InputEvent.BUTTON_DOWN, _buttonDownHandler);

In your event handler, you can then check the name of the button which was pressed, to see which action you need to perform:

//
// Handle a button being pressed
private function _buttonDownHandler(event:InputEvent):void
{
if(event.buttonName == InputButtonNames.UP)
{
// Do something
}
else if (event.buttonName == InputButtonNames.DOWN)
{
// Do something else
}
else if (event.buttonName == InputButtonNames.SELECT)
{
// Do something else
}
}

The InputButtonNames class contains the names of common buttons which appear on TV remotes. Feel free to add your own names to this class as necessary.

Key/Button Mappings

InputController comes pre-configured with the most common mappings you will need to use for simulating a TV remote with your computer keyboard. However, if you need to add your own, it’s really easy.

Find the _initKeyMappings() method, and take a look at how a mapping is defined:

// Select button
_mappings[Keyboard.SPACE] = InputButtonNames.SELECT;
_mappings[Keyboard.ENTER] = InputButtonNames.SELECT;

To add your own, just choose the key you want to map, and the InputButtonNames constant you want to map it to. You can also define your mappings numerically:

// R to RED
_mappings[82] = InputButtonNames.RED;

Hopefully that should be everything you need to know. If you have any questions, please feel free to ask them in the comments section.

Featured Projects BBCiPlayer on BT Vision LOVEFiLMPlayStation®3 App PushbuttonpbRemote LOVEFiLMiPad App

© Pushbutton 2010