Actionscript 3: Quick swipe logic for touch devices

If you are trying to simulate a swipe behavior like iOS devices, you would notice two things.

One is that if you drag a slide beyond the half way point, it will snap to the next slide, otherwise it will snap back to its original position.

Second is that if you do a quick swipe, it will go to the next position regardless if you passed the center point.

To achieve that quick swipe calculation, this is the logic you need.
First the variables:

private var xpos1:Number
private var xpos2:Number
private var time1:uint;
private var time2:uint;

Next is the mouse down event:

private function onMouseDown(event:MouseEvent):void
{
  this.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
  this.addEventListener(Event.ENTER_FRAME, onEnterFrame);

  xpos2 = this.mouseX;
  xpos2 = this.mouseX;
  time1 = getTimer();
  time2 = getTimer();
}

Then in the EnterFrame:

private function onEnterFrame(event:Event):void
{
  xpos1 = xpos2;
  xpos2 = this.mouseX;
  time1 = time2;
  time2 = getTimer();
}

and the actual logic in the mouse up event;

private function onMouseUp(event:MouseEvent):void
{
  this.stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
  this.removeEventListener(Event.ENTER_FRAME, onEnterFrame);

  var time:Number = (getTimer() - time1) / 500;
  var velocity:Number = (this.mouseX - xpos1) / time;
  trace(velocity);
}

The velocity can now be used to find a good tolerance for the quick swipe.

Author: mark

Creative technologist

Leave a Reply

Your email address will not be published. Required fields are marked *