views:

302

answers:

2

now I'm trying to make the keyboard events to stop repeating.

My idea was to have a true and false condition for when the key is pressed so that it wont repeat if the key is down already.

//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);
}

doing this makes the key loop over and over without a keyboard event I think i need to add a "&& keyDown..." to "if (this.soundplayed==true)" but i dont know how to do it without getting errors

here is the keyboard player i'm trying to fix http://soulseekrecords.org/psysci/animation/piano.html

A: 

I'm not sure what you are doing on these frames.. Is that 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);
}

Notice that the keydown event listener will now execute once -- I mean.. at least the if branch -- as the soundplayed variable is used as a locking mechanism. It'll only execute again after keyup's been executed (this.soundplayed = false).

MrKishi
this worked, thank you so much
psy-sci
+2  A: 

Just another (perhaps a bit more general) way to write what Kishi already 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 repeating was disabled. If you need to do something when the key is up, put that code in the keyUp function, or maybe call a processKeyUp function defined like processKeyDown.

Juan Pablo Califano
i have not tried this yet, but thank you also
psy-sci