/* Momentum Object ver. 0.1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Author: matt carpenter http://orangesplotch.com License: This code is released under the Creative Commons Attribution-ShareAlike 2.5 License http://creativecommons.org/licenses/by-sa/2.5/ Extend a MovieClip to allow it to be thrown. */ class MomentumObject extends MovieClip { // define the class constants private static var DAMPING_FACTOR = 0.98; private static var MAX_SPEED = 40; private static var MIN_SPEED = 0.5; private static var CONSTRAIN_TO_STAGE = true; private var lastFramePosition:Object; private var velocity:Object; private var isDragging:Boolean; // initialize everything in the class constructor function MomentumObject () { this.lastFramePosition = new Object(); this.velocity = new Object(); this.lastFramePosition.x = 0; this.lastFramePosition.y = 0; this.velocity.x = 0; this.velocity.y = 0; this.isDragging = false; // add handlers this.onEnterFrame = enterFrameHandler; this.onPress = pressHandler; this.onRelease = releaseHandler; this.onReleaseOutside = releaseHandler; } // Here is where all the action happens // If the ball is being dragged, save its velocity // If the ball is free, keep it moving along function enterFrameHandler () : Void { if (this.isDragging) { // calculate and save the object's velocity this.velocity.x = this._x - this.lastFramePosition.x; this.velocity.y = this._y - this.lastFramePosition.y; trace (this.velocity.x + ', ' + this.velocity.y); // limit the velocity to MAX_SPEED if ( Math.sqrt(this.velocity.x*this.velocity.x + this.velocity.y*this.velocity.y) > MomentumObject.MAX_SPEED ) { var velAng:Number = Math.atan2( this.velocity.y, this.velocity.x ); this.velocity.x = MomentumObject.MAX_SPEED * Math.cos( velAng ); this.velocity.y = MomentumObject.MAX_SPEED * Math.sin( velAng ); } // save the current location to the lastFramePosition this.lastFramePosition.x = this._x; this.lastFramePosition.y = this._y; } else { // the object is not being dragged, so keep it moving // if the velocity is small enough, just set it to zero if ( Math.sqrt( this.velocity.x*this.velocity.x + this.velocity.y*this.velocity.y ) < MomentumObject.MIN_SPEED ) { this.velocity.x = 0; this.velocity.y = 0; } this._x += this.velocity.x; this._y += this.velocity.y; // slow down the ball by the DAMPING_FACTOR this.velocity.x *= MomentumObject.DAMPING_FACTOR; this.velocity.y *= MomentumObject.DAMPING_FACTOR; if (MomentumObject.CONSTRAIN_TO_STAGE) { // bounce the ball off of the edges of the stage if (this._x > Stage.width) { this._x = Stage.width; this.velocity.x *= -1; } if (this._x < 0) { this._x = 0; this.velocity.x *= -1; } if (this._y > Stage.height) { this._y = Stage.height; this.velocity.y *= -1; } if (this._y < 0) { this._y = 0; this.velocity.y *= -1; } } } } function pressHandler () : Void { this.startDrag(); this.isDragging = true; } function releaseHandler () : Void { this.stopDrag(); this.isDragging = false; } }