Flash Tip Collection - Tip 1 - distance between 2 points
/**
* Copyright YoupSolo ( http://wonderfl.net/user/YoupSolo )
* GNU General Public License, v3 ( http://www.gnu.org/licenses/quick-guide-gplv3.html )
* Downloaded from: http://wonderfl.net/c/leaD
*/
package
{
import flash.display.DisplayObjectContainer;
import flash.display.LineScaleMode;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.geom.Point;
import flash.text.Font;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
/**
*
* @author YopSolo
* Cool to know that there is a built-in method to do the job :)
* ** ** ** ** ** ** ** ** **
* Note : if you need better performance (in a loop for example ) Point.distance
* use
* dist = Math.sqrt(dx * dx + dy * dy);
*
* This way to compute distance is faster than the static build-in method
*/
public class Main extends Sprite
{
private const FRAMERATE:int = 0;
public function Main():void
{
if (stage)
init();
else
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// run the swf
run();
}
// == APP ==
private function run():void
{
// define 2 Points !
var A:Point = new Point(80, 80);
var B:Point = new Point(280, 280);
// display the result using Point.distance(p1,p2); static method
buildTextField(this, 'TIP 1 : Calculate the distance between 2 points.' );
buildTextField(this, 'Point.distance(p1:Point, p2:Point), Static method of the Point class.',0 ,20 );
buildTextField(this, 'Distance Between A' + A.toString() + ' and B' + B.toString() + ' is : ' + Point.distance(A, B).toFixed(2), 0, 36);
// drawing the result for fun
this.graphics.beginFill(0xCC0000);
this.graphics.drawCircle(A.x, A.y, 3.5); // thx to stage quality low ^^
this.graphics.drawCircle(B.x, B.y, 3.5);
this.graphics.endFill();
this.graphics.lineStyle(2, 0xFFFF00, 1, true, LineScaleMode.NONE);
this.graphics.moveTo(A.x, A.y);
this.graphics.lineTo(B.x, B.y);
buildTextField(this, 'A' + A.toString(), A.x + 12, A.y - 9);
buildTextField(this, 'B' + B.toString(), B.x + 12, B.y - 9);
}
private function buildTextField(doc:DisplayObjectContainer, txt:String, x:int = 0, y:int = 0):TextField
{
var fmt:TextFormat = new TextFormat;
fmt.color = 0xFFFFFF;
fmt.font = 'Arial';
fmt.size = 11;
var tf:TextField = new TextField;
tf.autoSize = TextFieldAutoSize.LEFT;
tf.opaqueBackground = 0x333333; // opaque background allow a perfect font rendering even in StageQuality.LOW mode
tf.selectable = false;
tf.defaultTextFormat = fmt;
tf.text = txt;
tf.x = x;
tf.y = y;
doc.addChild(tf);
return tf;
}
}
}