AS3:用速度滑动手势

时间:2014-07-17 13:05:03

标签: actionscript-3 flash touch

所以我想为我的滑动手势添加速度。目前我在滑动时移动10像素,但我想让它以速度移动,这样用户就可以在屏幕上抛掷对象。这是我正在使用的对象移动10像素的代码。

function onSwipe (e:TransformGestureEvent):void{
    player_mc.gotoAndStop(5);
    if (e.offsetX == 1) { 
        //User swiped towards right
        player_mc.x += 10; 
    }
    if (e.offsetX == -1) { 
        //User swiped towards left
        player_mc.x -= 10;
    } 
    if (e.offsetY == 1) { 
        //User swiped towards bottom
        player_mc.y += 10; 
    }
    if (e.offsetY == -1) { 
        //User swiped towards top
        player_mc.y -= 10;
    } 

    if(collision(player_mc.cp, level_mc))
    {
        player_mc.x = player_mc.prevX;
        player_mc.y = player_mc.prevY;
    }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

以下是一种可以执行此操作的方法:(如果在移动设备上使用,您将需要将鼠标事件替换为触摸事件)

player_mc.addEventListener(MouseEvent.MOUSE_DOWN,startSwipe);
player_mc.addEventListener(MouseEvent.MOUSE_UP,endSwipe);

var velocity:Point = new Point(); //this stores the current velocity of the object
var previous:Point = new Point(); //this stores the previous frames x/y of the object.

var isDragging:Boolean = false;
var friction:Number = .85;  //this how quickly to slow down the object once the mouse is released - smaller the number (must be less than 1) the quicker the object will slow/stop

function startSwipe(e){
    isDragging = true;
    player_mc.startDrag(false);
    this.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
}

function enterFrameHandler(e):void {
    if(isDragging){
        velocity.x += player_mc.x - previous.x; //we're adding the new velocity to the old one, then dividing in half to average the value - this makes it seem smoother
        velocity.y += player_mc.y - previous.y;
        velocity.x *= .5; //dividing in half
        velocity.y *= .5;

        previous.x = player_mc.x;
        previous.y = player_mc.y;


    }else{
        velocity.x *= friction;  //gradually slow down the object
        velocity.y *= friction;

        player_mc.x += velocity.x;
        player_mc.y += velocity.y; 

        if(velocity.x < .05 && velocity.y < .05){ //once it gets slow enough, stop the enter frame handler
            this.removeEventListener(Event.ENTER_FRAME,enterFrameHandler);
        }
    }
    trace(velocity);
}

function endSwipe(e){
    player_mc.stopDrag();
    isDragging = false;
}