Domanda

I'm creating a game that requires the simultaneous pressing of keys as a confirmation.

Currently, I am attempting to use charCode with && conditionals in an if statement:

function reportKeyDown(event:KeyboardEvent):void 
{ 
    if (event.charCode == 97 && 109 && 13)
    {
     gotoAndStop(30) 
    }
    else {
        gotoAndStop(20)
        //subtract 5hp
    }
} 
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);

So far it will only recognize the first key. Any ideas on how to solve this?

È stato utile?

Soluzione

One possible solution is to save keyCodes in an array and check which keys was pressed after a short time

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
var timer:Timer=new Timer(100);
var tmpKeys:Array=[];
timer.addEventListener(TimerEvent.TIMER,reportKeyDown);
function keyDownHandler(e:KeyboardEvent):void{ 
    trace(e.keyCode);
    tmpKeys.push(e.keyCode);
    timer.start();
} 
function reportKeyDown(e:TimerEvent):void{
    if(keysAreDown([Keyboard.N,Keyboard.P])) //check for simultaneous pressing of 'n' and 'p'
        trace("yesss!");
    else
        trace("nooo!");
    tmpKeys=[];
    timer.stop();
}
function keysAreDown(keys:Array):Boolean{
    for each(var key:int in keys)
        if(tmpKeys.indexOf(key)==-1)
            return false;
    return true;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top