『矢量』Vector也稱『向量』它其實是『抽象量』.它可以有多種解析如『位置』『速度』『加速度』『方向』『距離』.因為用於2D遊戲開發定義2D『矢量』
public class VECTOR2D {
浮點數儲存2D矢量
public float x,y;
角度轉弧度
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);
購造函式初此為0
public VECTOR2D(){
x=y=0;
}
購造函式並設定x與y
public VECTOR2D(float x,float y){
this.x = x;
this.y = y;
}
返回新2D『矢量』拷貝
public VECTOR2D Copy(){
VECTOR2D v;
v=new VECTOR2D(x,y);
return v;
}
重設2D矢量
public VECTOR2D set(VECTOR2D v){
this.x = v.x;
this.y = v.y;
return this;
}
2D矢量加法
public VECTOR2D Add(VECTOR2D v){
this.x = this.x + v.x;
this.y = this.y + v.y;
return this;
}
2D矢量減法
public VECTOR2D Sub(VECTOR2D v){
this.x = this.x – v.x;
this.y = this.y – v.y;
return this;
}
2D矢量乘法等於對矢量進行縮放.
public VECTOR2D Mul(float scalar){
this.x = this.x * scalar;
this.y = this.y * scalar;
return this;
}
計算2D矢量長度
public float Len(){
float len;
len = (float) Math.sqrt(xx+yy);
return len;
}
2D矢量單位化,長度為1
public VECTOR2D Normer(){
float len;
len = Len();
if(len != 0) {
x = x / len;
y = y / len;
}
return this;
}
計算2D矢量角度
public float Angle(){
float angle = 0;
angle = (float)Math.atan2(y,x)*RADIANS_TO_DEGREES;
if(angle<0)
angle += 360;
return angle;
}
計算兩2D矢量角度在(0~360)度之間
public float Angle(VECTOR2D v){
float angle = 0;
float distanceX,distanceY;
distanceX = this.x – v.x;
distanceY = this.y – v.y;
angle = (float)Math.atan2(distanceY,distanceX)*RADIANS_TO_DEGREES;
if(angle<0)
angle += 360;
return angle;
}
2D矢量繞原點旋轉, angle為旋轉角度
public VECTOR2D rotate(float angle){
float rad = angle * DEGREES_TO_RADIANS; // 角度轉弧度
float cos = (float) Math.cos(rad);
float sin = (float) Math.sin(rad);
float newX = this.x * cos – this.y * sin;
float newY = this.x * sin + this.y * cos;
this.x = newX;
this.y = newY;
return this;
}
計算兩個2D矢量之間距離
public float Dist(VECTOR2D v){
float distX = this.x – v.x;
float distY = this.y – v.y;
float dist = (float)Math.sqrt(distX*distX + distY * distY);
return dist;
}
計算兩2D矢量之間距離平方
public float DistSquared(VECTOR2D v){
float distX = this.x – v.x;
float distY = this.y – v.y;
float dist = distX*distX + distY * distY ;
return dist;
}
}