簡體   English   中英

一個角度軸如何轉換向量以匹配另一個方向?

[英]How does one angle axis transform a vector to match the direction of another?

我正在為一個學校項目制作太空游戲,而我的飛船的AI則依賴向另一艘飛船移動的能力。 我當前的實現無法正常工作,因為它會將飛船旋轉到目標矢量的兩個方向,因此偶爾攻擊的飛船將朝着完全相反的方向前進,而其他時候它將向正確的方向走。 任何反饋將不勝感激!

//ship heading (already calculated)
Vector3f heading /* = ... */;
heading.normalize();

//direction of enemy ship relative to ours
Vector3d direction = new Vector3f(enemy.x - ship.x, enemy.y - ship.y, enemy.z - ship.z);
direction.normalize();

//angle between vectors
float angle = heading.angle(direction);

//axis to rotate upon
Vector3f axis = new Vector3f();
axis.cross(heading, direction);
axis.normalize();

//initialize matrix to hold rotation
Matrix4f rot = new Matrix4f();
rot.setIdentity();

//rotate the ship if we are more than 10 deg off
if (angle > Math.toRadians(10)) {
    rot.setRotation(new AxisAngle4f(axis, rotationVelocity * deltaTime));
}

好吧,我已經找到了一種更好的方法,它涉及一些線性插值。

以下內容保持不變:

//ship heading (already calculated)
Vector3f heading /* = ... */;
heading.normalize();

//direction of enemy ship relative to ours
Vector3d direction = new Vector3f(enemy.x - ship.x, enemy.y - ship.y, enemy.z - ship.z);
direction.normalize();

//angle between vectors
float angle = heading.angle(direction);

現在,我計算要插值到方向矢量的航向矢量的百分比:

//calculate angle to rotate
float deltaRotation = rotationVelocity * deltaTime;

//calcuate percent of rotation 
float percent = Math.min(deltaRotation / angle, 1.0f);

//create interpolated vector representing the new forward direction
Vector3f inter = new Vector3f(heading.x + percent * (direction.x - heading.x), heading.y + percent * (direction.y - heading.y), heading.z + percent * (direction.z - heading.z));
inter.normalize();

現在我們可以創建新的旋轉矩陣:

//the object's default forward size without any transformations
Vector3f forward = new Vector3f(0.0f, 0.0f, 1.0f);

//rotation axis
Vector3f axis = new Vector3f();
axis.cross(forward, inter);
axis.normalize();

//New rotation matrix to be applied
Matrix4f rotationMatrix = new Matrix4f();
rotationMatrix.setIdentity();
rotationMatrix.setRotation(new AxisAngle4f(axis, forward.angle(inter)));

現在,我的船始終面向正確的方向! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM