![](/img/trans.png)
[英]How does one rotate relative to the camera in openGL or more specifically LWJGL?
[英]Rotate camera relative to a point
我需要從第三人稱視角圍繞玩家旋轉攝像機。 (沒有什么花哨)。
這是我嘗試的方法:
// Forward, right, and position define the plane - they have x,y,z components.
void rotate ( float angle, Vector interestPoint )
{
Vector oldForward ( Forward );
forward = forward * cos(angle) + right * sin(angle);
forward.Normalize();
right = forward.CrossProduct ( up );
right.Normalize();
position = ( position + old_forward * position.Distance( interestPoint ) ) - (forward * position.Distance( interestPoint ) );
this->angle += angle;
}
問題是,如果說只是左轉很多,則物體和相機之間的距離會增加。
對於非常簡單的orbit
攝像機,像大多數3rd person
冒險游戲一樣,您需要做以下四件事:
(如果您希望相機始終相對於目標定向,則還需要提供目標的定向,在這種情況下,我將僅使用世界方向)
有關參考,請參見球坐標系 。
您應該在水平控件上映射方位角(並在達到2 * PI
時使其成環旋轉),而極角應在垂直控件上進行映射(如果玩家選擇了該選項並將其夾在-PI
之間,則應該反轉和PI
如果與世界Up
向量平行( -PI
或PI
), -PI
注意基於世界向量的計算
該距離可以是固定的,也可以由樣條驅動,在這種情況下,我們將假定固定的距離。
因此,要計算您的位置,請從WorldForward
開始,它是指向通常被認為是您的向前軸的unit vector
,例如(1,0,0)
(在這里,如果我們要構建一個相對攝像機,我們將使用我們目標的前向矢量),然后將其反轉( * -1
)以“從目標”“到達您的相機”。
(以下是未經測試的偽代碼,但是您應該了解要點-另外,請注意,它可以簡化,我只是為了清楚起見)
下一步是使用我們的方位角rotate
此矢量,該方位角是相機的水平方向分量。 就像是:
Vector toCamera = WorldForward * -1;
Matrix horizontalRotation = Matrix.CreateRotationZ(azimuth); // assuming Z is up
Vector horizontalRotationPosition = horizontalRotation.Transform(toCamera);
此時,您有一台可以圍繞目標水平旋轉的攝像機,現在要添加另一個軸,只需使用極角旋轉再次進行變換即可:
Matrix verticalRotation = Matrix.CreateRotationY(polar); // assuming Y is right
Vector finalRotatedVector = verticalRotation.Transform(horizontalRotationPosition);
現在,我們得到的是一個unit vector
,使其指向相機應該是,如果你被乘以位置distance
,你想從你的目標保持並添加你的目標的位置,你應該把你的最終position
。 請記住,如果取反此單位矢量,則它代表相機的forward
矢量。
Vector cameraPosition = targetPosition + finalRotatedVector * distanceFromTarget;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.