数组获取键盘输入

时间:2014-05-07 19:32:52

标签: arrays actionscript-3 indexing

这段代码来自一个教程,我理解它 - 只是不是数组。我知道数组在索引中保存值(array[1] =某些东西,array[2] =东西......)

但阵列"键如何"在更新函数中有Keyboard.RIGHT值吗?

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

(因为,例如,为了给Pascal中的变量赋值,我必须写readln (array[1]) - 这会给用户输入array[1]的任何值。< / p>

所以,我不知道keys[]如何获得键盘输入:P

1 个答案:

答案 0 :(得分:1)

e.keyCode是一个整数。调用onKeyDown时,代码使用整数将数组中的值设置为true。

例如,如果在键盘上按下RIGHT键,e.keyCode将为39,因此代码与keys[39] = true;相同。

如果您查看键盘的文档,您会看到Keyboard.RIGHT被定义为39. http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/ui/Keyboard.html

在下一帧中,更新事件将触发。 当你编写一个没有==的if语句时,它就有用了,所以if语句实际上是在说

if(keys[39] == true) {
    ball.x += 5;
}