package BasicEntity { import flash.display.Graphics; import flash.display.Graphics; import flash.geom.Point; public class Vector2D { private var x:Number; private var y:Number; public function set X(_value:Number):void { x = _value; } public function get X():Number { return x; } public function set Y(_value:Number):void { y = _value; } public function get Y():Number { return y; } public function get Perp():Vector2D { return new Vector2D( -y, x); } public function Vector2D(_x:Number = 0,_y:Number = 0) { x = _x; y = _y; } public function Clone():Vector2D { return new Vector2D(x, y); } /** * 将向量改变为零向量,并返回 */ public function Zero():Vector2D { x = 0; y = 0; return this; } /** * 是否为零向量 */ public function IsZero():Boolean { return (x == 0 && y == 0); } /** * 获取向量大小 */ public function get Length():Number { return Math.sqrt(x * x + y * y); } /** * 设置向量大小 */ public function set Length(value:Number):void { var a:Number = Angle; x = Math.cos(a) * value; y = Math.sin(a) * value; } /** * 向量大小的平方 */ public function get LengthSQ():Number { return x * x + y * y; } /** * 设置向量方向 */ public function set Angle(value:Number):void { var len:Number = Length; x = Math.cos(value) * len; y = Math.sin(value) * len; } /** * 获取向量方向 */ public function get Angle():Number { return Math.atan2(y, x); } /** * 修改为模向量 */ public function Normalize():Vector2D { if (Length == 0) { x = 1; return this; } else { var len:Number = Length; x /= len; y /= len; return this; } } /** * 指定位置绘制指定颜色的向量 */ public function DrawVector(_graphics:Graphics, _clr:uint, _pos:Point):void { _graphics.lineStyle(1, _clr); _graphics.moveTo(_pos.x, _pos.y); _graphics.lineTo(x+_pos.x, y+_pos.y); } /** * 反转向量并返回 */ public function Reverse():Vector2D { x = -x; y = -y; return this; } /** * 判断是否是单位向量 */ public function IsNormalized():Boolean { return Length == 1; } /** * 点乘(内积) * 返回一个数字 */ public function DotProduct(_v2d:Vector2D):Number { return x * _v2d.x + y * _v2d.y; } /** * 叉乘(外积) * 返回一个新向量 */ public function CrossProduct(_n:Number):Vector2D { return new Vector2D(x * _n, y * _n); } /** * 向量减法 */ public function Subtract(_v:Vector2D):Vector2D { return new Vector2D(x - _v.x, y - _v.y); } /** * 向量加法 */ public function Addition(_v:Vector2D):Vector2D { return new Vector2D(x + _v.x, y + _v.y); } /** * 截取当前向量,并返回 */ public function Turncate(_max:Number):Vector2D { Length = Math.min(Length, _max); return this; } } }