[英]Rotate GameObject around pivot point over time
我使用以下代碼旋轉與另一個軸點相關的點:
Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) {
Vector3 dir = point - pivot; // get point direction relative to pivot
dir = Quaternion.Euler(angles) * dir; // rotate it
point = dir + pivot; // calculate rotated point
return point;
}
如何在一個特定的持續時間內旋轉該點,比如使用一個協程5秒?
修改了我的其他答案中的代碼以獲得此效果。 您可以閱讀它以了解lerp的工作原理。
改變了什么,為什么:
1.通過將Vector3.zero
傳遞給angle參數和while
循環之外的當前Object位置,從RotatePointAroundPivot
函數beginRotation
點。 這需要完成一次,因為結果將在while
循環中使用。
Vector3 beginRotPoint = RotatePointAroundPivot(objPoint.transform.position, pivot, Vector3.zero);
這樣做是因為lerp需要一個起點。 那個起點應該永遠不會改變,它打破了lerp功能。
2.在while
循環中生成每個幀的新角度。 這是通過從Vector3.zero
到目標角度進行的:
float t = counter / duration;
Vector3 tempAngle = Vector3.Lerp(Vector3.zero, angles, t);
3。找到最終的轉角旋轉。 這是通過將起點從#1傳遞到第一個參數,樞軸點到第二個參數,最后是從#2到第三個參數生成的當前角度來完成的。
Vector3 tempPivot = RotatePointAroundPivot(beginRotPoint, pivot, tempAngle);
4。最后,將#3的結果分配給objPoint.transform.position
而不是objPoint.transform.eulerAngles
因為您不僅要移動對象。 你也在旋轉它。
objPoint.transform.position = tempPivot;
完整代碼:
你的RotatePointAroundPivot
函數:
Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles)
{
Vector3 dir = point - pivot; // get point direction relative to pivot
dir = Quaternion.Euler(angles) * dir; // rotate it
point = dir + pivot; // calculate rotated point
return point;
}
修改了rotateObject
函數,我描述了上面改變了什么:
bool rotating = false;
IEnumerator rotateObject(GameObject objPoint, Vector3 pivot, Vector3 angles, float duration)
{
if (rotating)
{
yield break;
}
rotating = true;
Vector3 beginRotPoint = RotatePointAroundPivot(objPoint.transform.position, pivot, Vector3.zero);
float counter = 0;
while (counter < duration)
{
counter += Time.deltaTime;
float t = counter / duration;
Vector3 tempAngle = Vector3.Lerp(Vector3.zero, angles, t);
Vector3 tempPivot = RotatePointAroundPivot(beginRotPoint, pivot, tempAngle);
objPoint.transform.position = tempPivot;
Debug.Log("Running: " + t);
yield return null;
}
rotating = false;
}
用法 :
將在5秒內繞樞軸點旋轉物體180度:
//The GameObject with the pivot point to move
public GameObject pointToRotate;
//The Pivot point to move the GameObject around
public Transform pivotPoint;
//The angle to Move the pivot point
public Vector3 angle = new Vector3(0f, 180f, 0f);
//The duration for the rotation to occur
public float rotDuration = 5f;
void Start()
{
StartCoroutine(rotateObject(pointToRotate, pivotPoint.position, angle, rotDuration));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.