Disabling repeated keyboard down event in as3
now i am trying to stop repeating keyboard events.
My idea was to have a true and false condition when the key is pressed so that it doesn't repeat if the key has already gone.
//Mouse Event Over
keyCButton.addEventListener(MouseEvent.MOUSE_OVER, function(){gotoAndStop(2)});
//Variable
var Qkey:uint = 81;
//Key Down Event
stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
var soundplayed = false;
function keydown(event:KeyboardEvent){
if (event.keyCode==Qkey) {
this.soundplayed=true;
}
}
if (this.soundplayed==false){
gotoAndPlay(3);
}
//Key Up Event
stage.addEventListener(KeyboardEvent.KEY_UP, keyup);
function keyup(event:KeyboardEvent){
this.soundplayed=false;
gotoAndStop(1);
}
this makes the key loop over and over again without keyboard event I think I need to add "& & keyDown ..." to "if (this.soundplayed == true)" but I don't know how to do it without getting errors.
here is the keyboard player i am trying to fix http://soulseekrecords.org/psysci/animation/piano.html
a source to share
I'm not sure what you are doing on these frames. Is this the complete code?
Anyway, you should try something like this:
// Mouse Events
this.keyCButton.addEventListener(MouseEvent.MOUSE_OVER, function():void{ gotoAndStop(2) });
// Variables
var Qkey:uint = 81;
var soundplayed = false;
// Keyboard events
this.stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
this.stage.addEventListener(KeyboardEvent.KEY_UP, keyup);
// Event listeners
function keydown(event:KeyboardEvent){
if (event.keyCode == Qkey && !this.soundplayed) {
this.soundplayed = true;
this.gotoAndPlay(3);
}
}
function keyup(event:KeyboardEvent){
this.soundplayed = false;
this.gotoAndStop(1);
}
Note that the keydown event listener will execute once - I mean .. at least the if branch, since the sound variable is used as a blocking mechanism. It will only execute after keyup has started (this.soundplayed = false).
a source to share
Another (perhaps more general) way to write what Kishi suggested:
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUp);
var downKeys:Dictionary = new Dictionary();
function keyDown(e:KeyboardEvent):void {
if(!downKeys[e.keyCode]) {
downKeys[e.keyCode] = true;
processKeyDown(e);
}
}
function keyUp(e:KeyboardEvent):void {
delete downKeys[e.keyCode];
}
function processKeyDown(e:KeyboardEvent):void {
trace(e.keyCode);
}
The processKeyDown function will be called as if keydown repetition had been disabled. If you need to do something when the key is inserted, put this code in the keyUp function, or perhaps call the processKeyUp function defined as processKeyDown.
a source to share