三維座標旋轉實現

推導

三維座標的旋轉其實挺容易理解的。
首先需要有個旋轉中心O(x,y,z)O(x,y,z)
其次是我們的旋轉點P(x1,y1,z1)P(x_1,y_1,z_1),
那麼可知旋轉點PP的相對座標爲P(x1x,y1y,z1z)P'(x_1-x,y_1-y,z_1-z)

此時我們開始旋轉。因爲座標系有三個軸,那麼旋轉其實就是繞着任意的兩個軸進行旋轉(當然三個軸也是可以的,但是兩個軸足以實現三個軸的效果了)

繞着某一軸進行旋轉的過程中,該軸對應的座標是不產生變化的,那麼實際上變化的座標就是在一個二維平面上,此時就又轉化爲二維旋轉問題。

二維座標旋轉問題

假設已知A(x1,y1)A(x_1,y_1),現圍繞原點O(0,0)O(0,0)旋轉β\beta角度,求現在位置B(x2,y2)B(x_2,y_2)

首先設AOAOxx軸夾角爲α\alpha,那麼BOBOxx軸夾角爲α+β\alpha+\beta,可知:

x2=x12+y12cos(α+β)x_2=\sqrt{x_1^2+y_1^2}*cos(\alpha+\beta)
y2=x12+y12sin(α+β)y_2=\sqrt{x_1^2+y_1^2}*sin(\alpha+\beta)
利用兩角公式展開:
x2=x12+y12(cos(α)cos(β)sin(α)sin(β))x_2=\sqrt{x_1^2+y_1^2}(cos(\alpha)cos(\beta)-sin(\alpha)sin(\beta))
y2=x12+y12(sin(α)cos(β)+cos(α)sin(β))y_2=\sqrt{x_1^2+y_1^2}(sin(\alpha)cos(\beta)+cos(\alpha)sin(\beta))
化簡:
x2=x1cos(β)y1sin(β)x_2=x_1cos(\beta)-y_1sin(\beta)
y2=y1cos(β)+x1sin(β)y_2=y_1cos(\beta)+x_1sin(\beta)

代碼實現

//三維座標
struct Position{
	float x;
	float y;
	float z;
};

//二維座標旋轉
void rotation(
	float &x,
	float &y,
	float degree)
{
	if(degree==0)
		return;
		
	float tempx = x * cos(degree) - y * sin(degree);
	float tempy = y * cos(degree) + x * sin(degree);
	x = tempx;
	y = tempy;
}

//三維座標旋轉
void rotation(
	Position &point,
	Position origin,
	float degreeX,
	float degreeY,
	float degreeZ)
{
    //求出到旋轉點的相對座標
	point.x -= origin.x;
	point.y -= origin.y;
	point.z -= origin.z;
	
	//分別繞X、Y、Z三軸進行旋轉
	rotation(point.y,point.z,degreeX);
	rotation(point.x,point.z,degreeY);
	rotation(point.x,point.y,degreeZ);
	
	//根據旋轉點轉換回原來的座標系
	point.x += origin.x;
	point.y += origin.y;
	point.z += origin.z;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章