符号偶尔会被困在边缘

时间:2015-04-10 20:44:32

标签: actionscript-3

我有一些代码,我想要一个符号(只是一个方形atm)在舞台内反弹。然而,偶尔它会卡在边缘。关于如何解决这个问题的任何建议?

其他一切都很好,包括惯性运动。

package  {
    import flash.display.MovieClip;
    import flash.events.*
    import flash.ui.Keyboard

    public class Unit extends MovieClip {

        var velocityX:Number = 1;
        var velocityY:Number = 1;
        var accellerationX:Number = 1;
        var accellerationY:Number = 1;
        var bounciness:Number = 1;
        var maxSpeed:Number = 10;

        public function Unit(){ 
            Key.initialize(stage);
            addEventListener("enterFrame", move);

        }

        private function move(e:Event){

            accellerate()
            if ((this.x<10)||(this.x>780)){
                velocityX *= -1;
                    if (velocityX>0){
                    velocityX -= bounciness;
                }
                if (velocityX<0){
                    velocityX += bounciness;
                }
                this.x += velocityX;
            }
            else{
                this.x += velocityX;
            }
            if ((this.y<10)||(this.y>520)){
                velocityY *= -1;
                if (velocityY>0){
                    velocityY -= bounciness;
                }
                if (velocityY<0){
                    velocityY += bounciness;
                }
                this.y += velocityY;
            }
            else {
            this.y += velocityY;
            }
        }

        private function accellerate(){

            if (Math.abs(velocityY) < maxSpeed){
                if (Key.isDown(Keyboard.UP)){
                    velocityY -= accellerationY;
                    trace("Accellerating UP");
                }
                if (Key.isDown(Keyboard.DOWN)){
                    velocityY += accellerationY;
                    trace("Accellerating DOWN");
                }
            }
            if (Math.abs(velocityX) < maxSpeed){
                if (Key.isDown(Keyboard.RIGHT)){
                    velocityX += accellerationX;
                    trace("Accellerating RIGHT");
                }
                if (Key.isDown(Keyboard.LEFT)){
                    velocityX -= accellerationX;
                    trace("Accellerating LEFT");
                }
            }
            if (Key.isDown(Keyboard.SPACE)){
                velocityX = 0;
                velocityY = 0;
        }

        }
    }

}

1 个答案:

答案 0 :(得分:0)

您的问题如下:

if ((this.x<10)||(this.x>780)){
    velocityX *= -1;

你切换了volocityX,但可能发生的事情是在下一帧,它仍然符合if条件(没有移动到另一个方向足够远)所以它只是来回走动帧从-1到1.

做这样的事情:

if(this.x < 10 && velocity == -1) velocity = 1;  //If it's near the left edge, and still moving to the left, change direction
if(this.x > 780 && velocity == 1) velocity = -1;

这样,当你走错路时,你只是在翻转方向。

重复speedY东西