flash的Vector3D是用来描述3维位移,方法属性命名和C#的Vector3D惊人的一致!要了解这个类必须先了解向量,在游戏中我们用向量来表示场景中的光照、加速度、速度、各种重要参考线等;点是三维空间中的某个坐标,是绝对的,它的值是参照原点的,而向量用于表示力和速度等具有方向和大小的量, 通常用具有长度和方向的线段来表示,虽然他们都具有三个分量,但对于向量,如果将向量放在坐标系中的任何位置(平移),都不会改变其性质,因为向量表示的是方向和大小,与位置距离无关,它的值是相对与基准点的。
三维空间的表示如下
向量的长度:向量的大小(或长度)称为向量的模
public function getlength():Number{
if(lengthSquared == 0 ){
return0;
}
return Math.sqrt(lengthSquared);
}
public function getlengthSquared():Number{
return x * x + y * y + z * z;
}
三维空间中两点的距离
public static function distance(pt1:Vector3D, pt2:Vector3D):Number{
return (pt1.subtract(pt2)).length;
}
![](https://i-blog.csdnimg.cn/blog_migrate/e6e1c9d90ca2527715cfc1e21d4d11b1.jpeg)
public function add(a:Vector3D):Vector3D{
return newVector3D(this.x + a.x,this.y + a.y,this.z + a.z);
}
public functionincrementBy(a:Vector3D):void{
this.x += a.x;
this.y += a.y;
this.z += a.z;
}
向量减法![](https://i-blog.csdnimg.cn/blog_migrate/862ba730d18abb658cdbe09268faf412.jpeg)
public function subtract(a:Vector3D):Vector3D{
return newVector3D(this.x - a.x,this.y - a.y,this.z - a.z);
}
public functiondecrementBy(a:Vector3D):void{
this.x -= a.x;
this.y -= a.y;
this.z -= a.z;
}
public function dotProduct(a:Vector3D):Number{
return x * a.x + y * a.y + z * a.z;
}
根据公式A.B = |A||B|cos(a)得出两个向量之间的弧度的角度
public static function angleBetween(a:Vector3D, b:Vector3D):Number{
var val:Number = a.dotProduct(b) / (a.length * b.length);
return Math.acos(val);// * 180 / Math.PI
}
其中a是A和B在3D空间中的夹角。如果已知两个向量,使用数量积我们就可以通过计算求得两个向量的夹角
![](https://i-blog.csdnimg.cn/blog_migrate/bceb4c013895a44b3b39a4f380a65426.jpeg)
public function crossProduct(a:Vector3D):Vector3D{
}
数乘向量:实数λ与向量b的积是一个向量,记作:a=λb。规定:当λ为正时,同向;当λ为负时,反向;实数λ,叫做向量的系数。数乘向量的几何意义就是把向量沿着相同方向或反方向放大或缩小
this.x *= s;
this.y *= s;
this.z *= s;
}
向量比较
public functionequals(toCompare:Vector3D, allFour:Boolean = false):Boolean{
var isquals:Boolean = (toCompare.x == this.x && toCompare.y == this.y && toCompare.y == this.y) && (allFour ? toCompare.w == this.w : true);
return isquals;
}
public functionnearEquals(toCompare:Vector3D, tolerance:Number, allFour:Boolean = false):Boolean{
var isquals:Boolean = Math.abs(toCompare.x - this.x) < tolerance && Math.abs(toCompare.y - this.y) < tolerance && Math.abs(toCompare.z - this.z) < tolerance;
if(allFour){
isquals = isquals && Math.abs(toCompare.w - this.w) < tolerance;
}
return isquals;
}
向量的规范化: 向量的规范化也称(归一化)就是使向量的模变为1,即变为单位向量。可以通过将向量都除以该向量的模来实现向量的规范化。规范化后的向量相当于与向量同方向的单位向量,可以用它表示向量的方向。由于方向的概念在3D编程中非常重要,所以此概念也很重要,单位向量有很多重要的性质,在表示物体表面的法线向量时用的更是频繁
public function normalize():Number{
var len:Number = this.length
if(len == 0){
return 0;
}
scaleBy(1/len)
return len;
}
投影:一般用于透视
向量b在A方向的投影为a
public function project():void{
scaleBy(1/ this.w)
}
图来自互联网