Search code examples
actionscript-3

(Actionscript 3.0) How to fix this arrow control glitch?


Currently, I am trying to make a game, but I ran into a couple of problems. One of them is that I have to click the screen for the arrow controls to work. Is there anyway to fix that?

Secondly, the arrow keys work as intended, but the WASD keys do not. Why is that?

private function key_down(event:KeyboardEvent): void{
        if(event.keyCode == Keyboard.LEFT || event.keyCode == 65){
            leftPressed=true;  
        }
        if(event.keyCode == Keyboard.RIGHT || event.keyCode == 68){
            rightPressed=true;
        }
        if(event.keyCode == Keyboard.UP || event.keyCode == 87){
            upPressed=true;
        }
        if(event.keyCode == Keyboard.DOWN || event.keyCode == 83){
            downPressed=true;
        }
    }
    private function key_up(event:KeyboardEvent): void{
        if(event.keyCode == Keyboard.LEFT || event.keyCode == 65){
            leftPressed=false;
        }
        if(event.keyCode == Keyboard.RIGHT || event.keyCode == 68){
            rightPressed=false;
        }
        if(event.keyCode == Keyboard.UP || event.keyCode == 87){
            upPressed=false;
        }
        if(event.keyCode == Keyboard.DOWN || event.keyCode == 83){
            downPressed=false;
        }
    }

Note: In another part of the code, I defined how the player moves if leftPressed, rightPressed, downPressed and upPressed is true or false.


Solution

  • Here's a very simplified version of your code, which you should test directly in an .fla file:

    stage.addEventListener(KeyboardEvent.KEY_DOWN, keydown);
    
    var leftPressed:Boolean;
    
    function keydown(event:KeyboardEvent): void
    {
        //if(event.keyCode == Keyboard.LEFT || event.keyCode == 65)
        if(event.keyCode == 65)
        {
            leftPressed=true;  
            trace('left Pressed');
        }
    
    }
    

    Notice that I've commented-out the Keyboard.LEFT line and replaced it with a line that tests only for the 'a' key. This should work on your system.