2014-05-25 39 views
3

我想在PVector類中使用heading()函數,但是我使用P3D併爲我的PVector設置了x,y和z。我將如何重新編寫此功能以使其可用於3D空間?我的目標是做這樣的事情:PVector Heading()for 3D Rotation

 size(100, 100, P3D); 
     PVector v = new PVector(.2, .11, .54); 
     rotate(v.heading()); //set rotation from PVector named v 
     line(0, 0, 10, 0); //draw line that will be rotated in correct direction 

上面的代碼,因爲v.heading不會顯示在三維空間中正確的旋轉()只適用於二維座標空間。我怎樣才能實現這個使用rotateX(),rotateY(),rotateZ()?我想盡可能避免使用四元數並使用旋轉函數。

在此先感謝!

回答

4

在2D中使用heading()函數將2D笛卡爾座標(x,y)轉換爲2D極座標(半徑,角度)。極座標的三維版本是spherical coordinates

spherical coordinates example

三維點P可以被表示爲三個線性座標(x,Y,Z)或一個線性座標和兩個角度(RHO,θ,Φ) 。 Rho是矢量的長度,theta是x-y平面中的角度,phi是到z平面的角度中的角度。這些方程描述的轉換:

rho = sqrt(x^2 + y^2 + z^2)

phi = arccos(z/rho)

theta = arctan(y/x)

您應該能夠使用rotateX()等使用這些角度的功能。請注意,這使用角度名稱theta和phi的數學約定;在物理學中,這些標籤與上面顯示的內容相反。

+0

感謝這麼多的響應Kevinsa5。你能指出我將如何在rotateX(),rotateY()和rotateZ()中使用它來使用這些變量實現正確的旋轉。 – Robbie

+0

我試過這個沒有運氣: rotateX(sin(theta)* cos(theta)); rotateY(cos(theta)); (sin(theta)* sin(theta)); – Robbie

+0

......以及:rotateX(rho * sin(phi)* cos(theta)); rotateY(rho * sin(phi)* sin(theta)); rotateZ(rho * cos(phi)); – Robbie

0

kevinsa5說的是什麼,除了使用反正弦函數來獲得高程。對方位角使用atan2函數(或更好的,只需使用矢量的2D標題方法)。並使用矢量的mag方法來確定它的大小。

rho = v.mag(); 

phi = asin(v.z/rho); 

theta = atan2(v.y, v.x); 

工作倒退,認爲 「X - Y - Z」,並嘗試:

PVector p = new PVector(v.mag(), 0, 0); // X 

rotateY3D(p, phi); // Y 

rotateZ3D(p, theta); // Z 

然後與原來v比較p