與『2D矢量』相比『3D矢量』僅是在x,y軸座標加上z軸座標.還有『點積』和『叉積』運算.與繞軸旋轉算法. 無左計算向量角度函式.
public class VECTOR3D {
3D浮點數座標
public float x,y,z;
角度轉弧度
public static float DEGREES_TO_RADIANS = ((1.0f/180.0f)* (float)Math.PI);
弧度轉角度
public static float RADIANS_TO_DEGREES = ((1.0f/(float)Math.PI)*180.0f);
用於繞軸旋轉
private static final float[] matrix = new float[16];
private static final float[] inVec = new float[16];
private static final float[] outVec = new float[16];
購造函式並設定x,y,z
public VECTOR3D(float x, float y,float z){
this.x = x;
this.y = y;
this.z = z;
}
拷貝3D矢量
public VECTOR3D Copy(){
VECTOR3D v;
v=new VECTOR3D(x,y,z);
return v;
}
重設3D矢量數值
public VECTOR3D set(VECTOR3D v){
this.x = v.x;
this.y = v.y;
this.z = v.z;
return this;
}
3D矢量加法運算
public VECTOR3D add(VECTOR3D v){
this.x = this.x + v.x;
this.y = this.y + v.y;
this.z = this.z + v.z;
return this;
}
3D矢量減法運算
public VECTOR3D sub(VECTOR3D v){
this.x = this.x – v.x;
this.y = this.y – v.y;
this.z = this.z – v.z;
return this;
}
3D矢量乘法(即縮放)
public VECTOR3D mul(float scalar){
this.x = this.x * scalar;
this.y = this.y * scalar;
this.z = this.z * scalar;
return this;
}
計算3D矢量長度
public float Len(){
float len;
len = (float) Math.sqrt(x*x+y*y+z*z);
return len;
}
3D矢量單位化,長度為1
public VECTOR3D normer(){
float len;
len = Len();
if(len != 0){
x = x / len;
y = y / len;
z = z / len;
}
return this;
}
繞某軸旋轉,先定義3D矢量,然後設置矩陣為零,然後用rotateM()旋轉,在乘以3D向量
public VECTOR3D rotate(float angle,float axisX,float axisY,float axisZ){
inVec[0] = x;
inVec[1] = y;
inVec[2] = z;
inVec[4] = 1;
Matrix.setIdentityM(matrix, 0);
Matrix.rotateM(outVec,0, angle, axisX, axisY, axisZ);// 選轉
Matrix.multiplyMV(outVec, 0, matrix, 0, inVec, 0);
x = outVec[0];
y = outVec[1];
z = outVec[2];
return this;
}
計算兩3D矢量之間距離
public float Dist(VECTOR3D v){
float distX = this.x – v.x;
float distY = this.y – v.y;
float distZ = this.z – v.z;
float dist = (float)Math.sqrt(distX*distX + distY*distY + distZ*distZ);
return dist;
}
計算兩個3D矢量之間距離平方
public float DistSquared(VECTOR3D v){
float distX = this.x – v.x;
float distY = this.y – v.y;
float distZ = this.z – v.z;
float dist = distX*distX + distY*distY + distZ*distZ;
return dist;
}
計算兩個3D向量叉積,叉積是一個向量,它與va和vb垂直.
void cross(VECTOR3D va, VECTOR3D vb){
x = ( (va.y * vb.z) – (va.z * vb.y) );
y = -( (va.x * vb.z) – (va.z * vb.x) );
z = ( (va.x * vb.y) – (va.y * vb.x) );
}
計算3D向量點積.返回值為浮點數
float dot(VECTOR3D v){
return( (x * v.x) + (y * v.y) + (z * v.z) );
}
3D向量取反數
VECTOR3D inverse(){
this.x = -this.x ;
this.y = -this.y ;
this.z = -this.z ;
return this;
}
}