EragonZZZZ -> RE: Flash Q&A Thread 5 - Flash Has Shares In Your Soul (8/26/2008 17:35:09)
|
I have to see your code to compress it, unfortunately. If you want to zing the .fla and .as files along, I can do that for you. It won't slow it down at all, methinks. In fact, you'll probably make Flash do less thinking and therefore go faster. Anywho, here's the bare bones of the keyinput class. No more "function onKeyDown()". READ THIS FIRST: The code below is not commented and therefore you will have no idea how to use it if you don't read here first. 1) Copy and paste the code into an .as file, save it as "InputReader.as", and put it in the folder with the .fla you want to use it with. 2) On your .fla, create a new variable: var keyReader:InputReader = new InputReader(); 3) To assign a key to a function, you simply use the function "assignKeyFunction()." Here's how it works: keyCode = the Flash code of the key you want it to listen for...you can use Key.LEFT, Key.RIGHT, etc. if you want. func = the name of the function you want to run when the key is pressed. It is important to note that you must NOT include parenthesis. Only the name. runHold= set to "true" if you want the function to run repeatedly if the user holds the key, "false" if you want it to run only when they press the key. sendVal = Optional value. Use this if you'd like to pass a value to the function every time it runs. Useful if you have multiple keys attached to one function. 4) Finally, create an onEnterFrame() event and put the function "keyListener.iterate()" in it. You're done. 5) Right now, you can only set a function to be called on a keypress/keyhold, but it's still neater than using if(key.isDown()) sixty billion times. More functionality will come as I need it for my own projects ^___^ class InputReader {
var keys:Array;
var stat:Array;
var functions:Array;
public function InputReader() {
keys = new Array();
stat = new Array();
functions = new Array();
}
public function assignKey(keyCode:Number):Void {
keys.push(keyCode);
stat.push(0);
}
public function assignKeyFunction(keyCode:Number, func:Function, runHold:Boolean, sendVal:Object) {
assignKey(keyCode);
functions.push(new Array(func,runHold,sendVal));
}
public function iterate():Void {
for(var i in keys) {
if(Key.isDown(keys[i])){
switch(stat[i]){
case 0:
stat[i] = 1;
break;
case 1:
stat[i] = 2;
break;
case 2:
break;
}
}else{
stat[i] = 0;
}
}
for(var i in functions) {
switch(stat[i]){
case 0:
break;
case 1:
if(functions[i][2] != undefined)
functions[i][0](functions[i][2]);
else
functions[i][0]();
break;
case 2:
if(functions[i][1])
if(functions[i][2] != undefined)
functions[i][0](functions[i][2]);
else
functions[i][0]();
break;
}
}
}
}//While you, in using this code, are authorized to use it, modify it, build from it, or copy it in any way you please, you may not pass this off as your own work.
|
|
|
|