[英]How to AddTorque towards an object
我有兩個立方體。 其中一個必須始終朝向另一個旋轉。 問題是另一個立方體總是改變它的位置。 這是一張圖片,解釋了我需要什么。
我試圖將扭矩添加到它們之間的方向,但沒有奏效。
transform.GetComponent<Rigidbody>().AddTorque(transform.position - OtherCube.transform.position * 10f * Time.smoothDeltaTime);
任何幫助表示贊賞!
編輯:
旋轉立方體的面並不總是看着另一個立方體,所以它應該旋轉而不看另一個立方體。 (我的意思是它應該從最近的面或邊緣或任何地方旋轉。沒關系)。
您可以使用叉積來找到您感興趣的軸,同時考慮到地面的方向:
private Rigidbody rb;
void Start() { rb = GetComponent<Rigidbody>(); } // cache results of GetComponent
void TurnTowards()
{
Vector3 groundDirection = Vector3.down;
Vector3 towardsOther = (OtherCube.transform.position - transform.position).normalized;
Vector3 rotateAxis = Vector3.Cross(towardsOther, groundDirection);
float rotateMagnitude = 500f; // tune as necessary
rb.AddTorque(rotateMagnitude * Time.smoothDeltaTime * rotateAxis);
}
我認為如果你使用一個空物體作為立方體的父親,凍結立方體中的運動會更容易。
有了這個,你可以讓父級只看另一個立方體,而立方體只是在他的 X 軸上添加扭矩,代碼將像這樣簡單:
private Transform parent;
private Rigidbody rb;
void Start() {
parent = transform.parent;
rb = GetComponent<Rigidbody>();
}
void Update()
{
Quaternion rot = transform.rotation;
parent.LookAt(otherCube.transform);
transform.rotation = rot;
rb.AddTorque(rotateMagnitude * parent.right);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.