Auto-define inputs from a file

(Jacob Albano) #1

Here’s a tiny function I’m using in my current FP project. I like keeping as much as possible in data files instead of directly in code, so this is how I set up my input definitions.

public static function defineInput(xml:XML):void
    for each (var input:XML in xml.children()) 
        var keys:Array = [];
        var keyNames:Array = String(input)
            .replace(/[\s\r\n]+/gim, "")
        for each (var key:String in keyNames) 
        Input.define(, keys);

You give it an xml file that looks like this, using the static property names from the Key class. Comma-separated values will result in multiple options for the same input.


And then you call the function like this:


And voilà! Your inputs are automatically defined. You can use them by querying the Input class with the names you used in the file. Any time you want to add more keys or input types, just edit the file.

var direction:int = 0;
if (Input.check("left")) direction--;
if (Input.check("right")) direction++;

if (Input.pressed("attack"))

if (Input.pressed("jump") && onFloor)

(Zachary Lewis) #2

Why not go with well-specified XML?

<?xml version="1.0"?>
  <Input name="jump">
  <Input name="attack">
  <Input name="left">
  <Input name="right">

Then use E4X to define those inputs (untested)!

public static function defineInput(xml:XML):void
  var input:XML;
  var keys:Array;
  var inputName:String;
  // Iterate through each defined Input.
  for each (input in xml.Input)
    // Save the name of the Input from the XML.
    inputName = input.@name;
    // This *should* put all the keys into the array.
    // If not, iterate through each Key.
    keys = input.Key;
    // Define the input.
    Input.define(inputName, keys);

(Jacob Albano) #3

Mainly because it’s really tedious to type. Each approach gives the same results, so I tend to go with the more convenient one. To each his own, of course.

(Zachary Lewis) #4

@jacobalbano I found a picture of you: :poop:

(Mike Evmm) #5

(Zachary Lewis) #6