[英]How to get an agent to face the direction of travel when strafing around a target? (Unity / C#)
我正在 Unity 中開發一個 FPS 游戲,我希望有一個代理(動畫蝙蝠)在目標周圍掃射。 一切正常,但是蝙蝠在圍繞目標掃射時面向固定方向,而不是面向行進方向。 我嘗試按照下面列出的代碼添加四元數旋轉(請參閱“面向正確方向”),但無濟於事。 我已經注釋掉了代碼部分,看看我是否可以確定問題所在,但這只會導致更多問題。 任何幫助將不勝感激。
代碼...
// Target position. The gameobject will circle around this position.
[SerializeField]
private Vector3 TargetPosition = new Vector3();
// Temp Position. Used to generate a new position on the circle.
private Vector3 tempPosition = new Vector3();
// Radius. Generated from the game objects current distance to the target.
float r;
// The current angle in the circle strafe.
float theta;
/// movement variables
private Vector3 currentTargetPos;
// Start is called before the first frame update
void Start()
{
// Get the radius. The distance to the target position.
r = Vector3.Distance(transform.position, TargetPosition);
// Default theta.
theta = Mathf.Acos((transform.position.x - TargetPosition.x) / r);
// Check quadrant and adjust.
if ((transform.position.x - TargetPosition.x) > 0 &&
(transform.position.y - TargetPosition.y) > 0)
{
Debug.Log("Quadrant 1");
}
if ((transform.position.x - TargetPosition.x) < 0 &&
(transform.position.y - TargetPosition.y) > 0)
{
Debug.Log("Quadrant 2");
}
if ((transform.position.x - TargetPosition.x) < 0 &&
(transform.position.y - TargetPosition.y) < 0)
{
Debug.Log("Quadrant 3");
theta = -theta;
}
if ((transform.position.x - TargetPosition.x) > 0 &&
(transform.position.y - TargetPosition.y) < 0)
{
Debug.Log("Quadrant 4");
theta = -theta;
}
Debug.Log("theta x = " + theta);
}
// Update is called once per frame
void Update()
{
// Get the actors circle strafe location.
tempPosition.x = TargetPosition.x + r * Mathf.Cos(theta);
tempPosition.z = TargetPosition.z + r * Mathf.Sin(theta);
tempPosition.y = transform.position.y;
// Update t.
theta += 0.2f * Time.deltaTime;
// Set the location.
transform.position = tempPosition;
// clear y to avoid up/down movement
currentTargetPos.y = transform.position.y;
Vector3 direction = currentTargetPos - transform.position;
// face in the right direction
direction.y = 0;
Quaternion rotation = Quaternion.LookRotation(-direction, Vector3.up);
transform.rotation = rotation;
}
// Draws debug objects in the editor and during editor play (if option set).
void OnDrawGizmos()
{
// Draw target position.
Gizmos.color = Color.red;
Gizmos.DrawSphere(TargetPosition, 0.2f);
}
}
Unity 有一個內置的 function 用於名為LookAt()
的變換,它采用Transform other
或Vector3 worldPosition
作為參數。 要實現它,您可以編寫transform.LookAt(TargetPosition)
。
請注意,這可能會影響依賴於本地旋轉的翻譯,因此如果您遇到問題,您還需要更改一些邏輯。 為了避免這種情況,您可能希望在移動之前重置旋轉,然后將旋轉移回需要的位置,或者使用世界空間而不是局部空間更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.