Example 3 - Auto Rotation with ENTER_FRAME

We add functionality to our octahedron example. After the user stops rotating the surface with the mouse, the surface keeps rotating with the last recorded "velocity". To accomplish that, we add a listener to the Stage which listens to Enter Frame event.

Download

The fla file linked below contains complete, exhaustively commented source code for the Flash movie above. We will discuss below only the portions of the code that are new to this part of the tutorial.

The Code

 

............................

/*
We add three variables that could be considered the 'velocity's' 'componets' and its 'magnitude'. The variables will be used for continuing rotation after the user releases the mouse.
*/

var velX:Number=0;

var velY:Number=0;

var velMag:Number=0;

............................

/*
In boardDown listener, we reset the velocity's components and magnitude to 0 so the user can stop automatic rotation with a click.
*/

function boardDown(e:MouseEvent):void {

prevX=spBoard.mouseX;

prevY=spBoard.mouseY;

velX=0;

velY=0;

velMag=0;

doRotate=true;

}

............................

/*
In boardMove listener, we set the velocity's components and magnitude based to the user's movement of the mouse.
*/

function boardMove(e:MouseEvent):void {

var locX:Number=prevX;

var locY:Number=prevY;

if(doRotate){

prevX=spBoard.mouseX;

prevY=spBoard.mouseY;

velX=2*(prevX-locX);

velY=2*(prevY-locY);

velMag=Math.abs(velX)+Math.abs(velY);

curTheta+=(prevX-locX);

curPhi+=(prevY-locY);

renderView(curTheta,curPhi);

e.updateAfterEvent();

}

}

/*
We add a listener to the Stage that listens to ENTER_FRAME event. If doRotate is false (that is, the user is not rotating the object) and the last recorded velocity has positive magnitude, the continuing rotation will take place.
*/

stage.addEventListener(Event.ENTER_FRAME,whenEnterFrame);

function whenEnterFrame(e:Event):void {

if(!doRotate && velMag>0){

curTheta+=velX;

curPhi+=velY;

renderView(curTheta,curPhi);

}

}

............................

 

Back to Advanced and Experimental              Back to Flash and Math Home

We welcome your comments, suggestions, and contributions. Click the Contact Us link below and email one of us.

Adobe®, Flash®, ActionScript®, Flex® are registered trademarks of Adobe Systems Incorporated.