Domanda

This code is from a tutorial, I do understand it - just not the array. I know arrays hold values in their indexes (array[1]=something, array[2]=something...)

But how does the array "keys" have the Keyboard.RIGHT value in the update function?

package 
{
    -imports here-

    public class Main extends Sprite 
    {
        var keys:Array = [];
        var ball:Sprite = new Sprite();

        public function Main():void 
        {
            ball.graphics.beginFill(0x000000);
            ball.graphics.drawCircle(0, 0, 50);
            ball.graphics.endFill;

            addChild(ball);

            ball.x = stage.stageWidth / 2;
            ball.y = stage.stageHeight / 2;

            ball.addEventListener(Event.ENTER_FRAME, update);
            stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
            stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
        }

        private function update(e:Event):void {
            if (keys[Keyboard.RIGHT]) {
                ball.x += 5;
            }            
        }

        function onKeyDown(e:KeyboardEvent):void {
            keys[e.keyCode] = true;
        }

        function onKeyUp(e:KeyboardEvent):void {
            keys[e.keyCode] = false;
        }
    }
}

(Because, to give a value to a variable in Pascal for an example, I'd have to write readln (array[1]) - this would give whatever value the user typed to array[1]).

So, I don't see how keys[] is getting keyboard input :P

È stato utile?

Soluzione

e.keyCode is an integer. When the onKeyDown gets called, the code uses the integer to set a value in the array to true.

For example, if the RIGHT key is pressed on the keyboard, e.keyCode would be 39, so the code is the same as keys[39] = true;.

If you look at the documentation for Keyboard you will see that Keyboard.RIGHT is defined as 39. http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/ui/Keyboard.html

On the next frame the update event fires. When you write an if statement without an ==, it kinda does it for, so the if statement is essentially saying

if(keys[39] == true) {
    ball.x += 5;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top