2010-04-30 60 views
2

現在我試圖讓鍵盤事件停止重複。禁用as3中的重複鍵盤按下事件

我的想法是有一個真實和錯誤的條件,當按鍵被按下時,如果鍵已經關閉,它不會重複。

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

這樣使得按鍵循環一遍又一遍沒有鍵盤事件 我想我需要添加一個「& &的keyDown ......」到「如果(this.soundplayed ==真)」,但我不知道如何做到這一點沒有得到錯誤

這裏是鍵盤手我試圖修復http://soulseekrecords.org/psysci/animation/piano.html

回答

0

我不知道你在做這些幀的.. 那是完整的代碼?

無論如何,你應該嘗試這樣的事:

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

注意,的keydown事件監聽器現在將執行一次 - 我的意思..至少如果分支 - 作爲soundplayed變量被用作鎖定機制。 只有在執行鍵盤後纔會再次執行(this.soundplayed = false)。

+0

這工作,非常感謝你 – 2010-05-03 14:01:45

3

只是另一個(或許有點更通用)的方式來寫什麼岸已經建議:彷彿KEYDOWN重複被禁用

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

的processKeyDown函數將被調用。如果您在啓動密鑰時需要執行某些操作,請將該代碼放入keyUp函數中,或者調用processKeyDown之類的processKeyUp函數。

+0

我還沒有嘗試過,但也謝謝你 – 2010-05-03 14:02:04