AS3 - 球超速

时间:2012-05-26 17:14:24

标签: actionscript-3 flash

我正在使用Flash Pro CS6创建一个小应用程序,我使用箭头键(使用Code Sippets制作)以每帧4像素的速度移动这个球。问题在于,每当我死了,我到达另一个框架,我可以重播并再次尝试游戏,但这次,球的速度是8像素/帧,并且每次重播游戏时这个数字都会保持正常。有没有办法解决这个问题?这是我正在使用的片段:

var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;

ball.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey); //I think the problem might be this "Enter Frame"
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);

function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
    ball.y -=  4;
}
if (downPressed)
{
    ball.y +=  4;
}
if (leftPressed)
{
    ball.x -=  4;
}
if (rightPressed)
{
    ball.x +=  4;
}
}

function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
    case Keyboard.UP :
        {
            upPressed = true;
            break;


        };
    case Keyboard.DOWN :
        {
            downPressed = true;
            break;


        };
    case Keyboard.LEFT :
        {
            leftPressed = true;
            break;


        };
    case Keyboard.RIGHT :
        {
            rightPressed = true;
            break;


    }
}
};

function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
    case Keyboard.UP :
        {
            upPressed = false;
            break;


        };
    case Keyboard.DOWN :
        {
            downPressed = false;
            break;


        };
    case Keyboard.LEFT :
        {
            leftPressed = false;
            break;


        };
    case Keyboard.RIGHT :
        {
            rightPressed = false;
            break;


    }
}
};

1 个答案:

答案 0 :(得分:1)

它的样子,你每次gotoAndPlay第一帧时都创建一个新的球实例 - 但是仍然有一个事件监听器附加到原始实例上,即使它从舞台上移除后也是如此。

因此,在每个新的ENTER_FRAME上,该方法不仅被调用一次,而且每次被调用一次。解决方案是在“你死”时删除事件监听器,或使用弱引用,以便可以干净地删除球实例。

BTW这是你的脚本的简短版本 - 不需要所有那些if-和switch-statement,以及实例变量:

var keyPressed:int = -1;
ball.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);

function fl_SetKeyPressed(event:KeyboardEvent):void {
    keyPressed = event.keyCode;
}

function fl_UnsetKeyPressed(event:KeyboardEvent):void {
    keyPressed = -1;
}

function fl_MoveInDirectionOfKey(event:Event) {
    ball.y += keyPressed == Keyboard.UP ? -4 : keyPressed == Keyboard.DOWN ? 4 : 0;
    ball.x += keyPressed == Keyboard.LEFT ? -4 : keyPressed == Keyboard.RIGHT ? 4 : 0;
}