ActionScript DragRotatePedal

In an effort to duplicate the behaviour of this Flash5 example in ActionScript 3.0, I came up with the following, adapted for use with slightly different objects to simulate the rotation of a bike pedal:

package {

	import flash.display.*;
	import flash.events.*;
	import flash.utils.Timer;
	
	public class DragRotatePedal extends Sprite {
		
		// Main document class
		
		public var angle:Number;
		public var timer:Timer;

		public function DragRotatePedal() {
			// add event listeners
			crank.pedal.addEventListener(MouseEvent.MOUSE_DOWN, rotatePedal);
			
			// trace mouse position every second
			// debug();
		}
			
		function rotatePedal(e:MouseEvent):void {
			// trace("Mouse DOWN on pedal");
			
			stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			
			function onMouseMove(e:MouseEvent):void {
				
				// get an angle to the mouse using atan2 (gets radians)
				angle = Math.atan2(mouseY - crank.y, mouseX - crank.x);
				
				// apply rotation to crank shaft by converting angle into degrees
				crank.rotation = angle * 180 / Math.PI;
				
				// rotate the pedal opposite to the crank shaft so it won't rotate along with it
				crank.pedal.rotation = -crank.rotation;
			}

			function onMouseUp(e:MouseEvent):void {
				//	trace("Mouse UP on pedal");
				stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			}
		}

		function debug():void {
			timer = new Timer(1000);
			timer.addEventListener(TimerEvent.TIMER, traceOutput);
			timer.start();
		}
		
		function traceOutput(e:TimerEvent):void {
			trace("mouseX: " + mouseX);
			trace("mouseY: " + mouseY);
		}
	}
}
Advertisements

About this entry