본문 바로가기

FLASH/AIRforAndroid

터치이벤트로 공던지기 구현

터치이벤트로 던지기 구현

아래의 소스로 퍼블리시하면 스마트폰에서 터치이벤트로 공을 선택한 후에 특정한 쪽으로 손가락을 옮기면서 떼면 공이 굴러갑니다.

마치 던지기를 구현하는 것과 같습니다.

공이 벽에 닿으면 멈추도록 구성되어 있습니다.



aFling.fla



import flash.events.Event;

import fl.transitions.Tween;


import fl.motion.easing.*;

import flash.events.TouchEvent;


var flingMotionX:Tween;

var flingMotionY:Tween;


Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;

var counter:uint = 1;

var origX:Number = ball.x;

var origY:Number = ball.y;


var finalX:Number = 0;

var finalY:Number = 0;


function updateCounter(evt:Event):void

{

counter++;

}


ball.addEventListener(TouchEvent.TOUCH_BEGIN, fl_TouchBeginHandler);

ball.addEventListener(TouchEvent.TOUCH_END, fl_TouchEndHandler);


var fl_DragBounds:Rectangle = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);


function fl_TouchBeginHandler(event:TouchEvent):void

{

try

{

flingMotionX.stop();

flingMotionY.stop();

}

catch (e:*)

{

}

counter = 1;

origX = ball.x;

origY = ball.y;

stage.addEventListener(Event.ENTER_FRAME, updateCounter);

event.target.startTouchDrag(event.touchPointID, false, fl_DragBounds);

}


function fl_TouchEndHandler(event:TouchEvent):void

{

stage.removeEventListener(Event.ENTER_FRAME, updateCounter);

finalX = ball.x;

finalY = ball.y;

event.target.stopTouchDrag(event.touchPointID);

calculateFling();

}


function calculateFling():void

{

var flingX:Number = (finalX - origX) / counter;

var flingY:Number = (finalY - origY) / counter;

var flingDuration:Number = counter/10;

var flingXFinal:Number = 0;

var flingYFinal:Number = 0;

if(flingDuration < 0.5)

{

flingXFinal = (flingX < 0) ? Math.max(0, ball.x + flingX*50) : Math.min(stage.stageWidth, ball.x + flingX*50);

flingYFinal = (flingY < 0) ? Math.max(0, ball.y + flingY*50) : Math.min(stage.stageHeight, ball.y + flingY*50);

}

else

{

flingXFinal = (flingX < 0) ? Math.max(0, ball.x + flingX*10) : Math.min(stage.stageWidth, ball.x + flingX*10);

flingYFinal = (flingY < 0) ? Math.max(0, ball.y + flingY*10) : Math.min(stage.stageHeight, ball.y + flingY*10);

flingDuration = 1;

}

flingMotionX = new Tween(ball, "x", Quadratic.easeOut, ball.x, flingXFinal, flingDuration, true);

flingMotionY = new Tween(ball, "y", Quadratic.easeOut, ball.y, flingYFinal, flingDuration, true);

}