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, "")
            .split(",");
            
        for each (var key:String in keyNames) 
        {
            keys.push(Key[key])
        }
        
        Input.define(input.name(), 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.

<keys>
    <jump>UP,SPACE</jump>
    <attack>X</attack>
    <left>LEFT</left>
    <right>RIGHT</right>
</keys>

And then you call the function like this:

defineInput(FP.getXml(YOUR_FILE_EMBED));

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++;
walk(direction);

if (Input.pressed("attack"))
    shoot();

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

(Zachary Lewis) #2

Why not go with well-specified XML?

<?xml version="1.0"?>
<Inputs>
  
  <Input name="jump">
    <Key>UP</Key>
    <Key>SPACE</Key>
  </Input>
  
  <Input name="attack">
    <Key>X</Key>
  </Input>
  
  <Input name="left">
    <Key>LEFT</Key>
  </Input>
  
  <Input name="right">
    <Key>RIGHT</Key>
  </Input>
  
</Inputs>

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