Detecting and responding to a rotation gesture

How to

Detect and respond to a rotation gesture.

BlackBerry device showing a directional arrow moving clockwise in the center of the screen. Shows the rotation gesture.

Solution

Set the input mode to GESTURE and add an event listener

// Enable dispatch of gesture
Multitouch.inputMode = MultitouchInputMode.GESTURE;

// Define the gesture to listen for and the name of the function to dispatch when it occurs
stage.addEventListener(TransformGestureEvent.GESTURE_ROTATE, onRotate);

Create the function that is called to react to your event

public function onRotate(event:TransformGestureEvent):void
{
    // For this example code the totalRotate variable 
    // Is assumed to be an integer in the root of the class
    // That keeps track of total rotation across events
	
    // Add event's rotation change to total rotation amount
    totalRotate = totalRotate + event.rotation;
	
    // Adjusting value to fit within -180 to +180 degrees
    if (totalRotate > 180)
    {
		totalRotate += -360;
	}
	else if (totalRotate <= -180)
    {
    	totalRotate += 360;
	}
	
    // Output results
    trace ("current rotation is "+totalRotate+" degrees, with a change of "+event.rotation+" degrees");
}

Build requirements

You must include the following classes in the class:

import flash.events.TransformGestureEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;

Discussion

To react to a rotation gesture, you should set the MultiTouchInputMode to GESTURE to dispatch gesture events. After you set the input mode, add an event listener to handle a GESTURE_ROTATE event. To add functionality, you can then evaluate the event.rotation values in the function called by that listener to detect rotation direction and respond accordingly.