推導
三維座標的旋轉其實挺容易理解的。
首先需要有個旋轉中心,
其次是我們的旋轉點,
那麼可知旋轉點的相對座標爲
此時我們開始旋轉。因爲座標系有三個軸,那麼旋轉其實就是繞着任意的兩個軸進行旋轉(當然三個軸也是可以的,但是兩個軸足以實現三個軸的效果了)
繞着某一軸進行旋轉的過程中,該軸對應的座標是不產生變化的,那麼實際上變化的座標就是在一個二維平面上,此時就又轉化爲二維旋轉問題。
二維座標旋轉問題
假設已知,現圍繞原點旋轉角度,求現在位置:
首先設與軸夾角爲,那麼與軸夾角爲,可知:
利用兩角公式展開:
化簡:
代碼實現
//三維座標
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;
}