![](/img/trans.png)
[英]How to throw an object and have it rotate around a sphere as if it were orbiting
[英]How do I rotate an object to a specific position around another object? (Essentially orbiting to specified position)
我有一顆行星和一顆月亮。 月亮是一個虛擬對象的父對象,該對象位於行星的中心(基本上為0,0,0)。 月亮可以繞地球自由旋轉(到任何位置)。 它應該與行星保持恆定的距離。
我想將月亮旋轉到某個特定點,盡管它需要保持直立。 也就是說,月球應始終相對於行星表面指向“上方”。 基本上,這就像一個“ moveTo”腳本,僅在我這種情況下,月亮才應該圍繞地球“旋轉”,直到到達我要尋找的點為止。
這是我到目前為止的內容,盡管我無法算出要使用的正確邏輯:
Vector3 targetDir = moveToPos - moon.transform.position;
float angle = Vector3.Angle( targetDir, moon.transform.up );
dummy.transform.RotateAround (moveToPos, moon.transform.up, angle);
我是否正確地考慮了這一點? 一旦完成這項工作,我便希望向月亮提供不同的Vector3
位置,並讓月亮在行星表面上向它們旋轉。 我已經搜索了類似的東西,但是找不到我想要的東西。
此屏幕快照中顯示的標記應顯示“ Rotate here”,但這實際上是我的場景:
通過將月亮嵌套在一個空的變換中,您已經使事情變得容易得多。 如果設置正確*,這意味着您不必直接操縱月球的transform
-您只需要旋轉容器對象,直到它面對目標位置為止。
* 這樣,我的意思是容器對象相對於行星位於(0,0,0),並且月亮僅沿z軸局部平移,因此它與容器的transform.forward
向量對齊。
如果將問題分解為更小的步驟,則更容易解決該問題:
Quaternion.LookRotation()
的好地方。 Quaternion.Lerp()
可用於實現此目的。 您可以按照以下步驟執行這些步驟:
Quaternion targetRotation;
Quaternion startRotation;
float progress = 1;
void SetTargetPosition(Vector3 position)
{
// Calculating the target direction
Vector3 targetDir = position - dummy.transform.position;
// Calculating the target rotation for the container, based on the target direction
targetRotation = Quaternion.LookRotation(targetDir);
startRotation = dummy.transform.rotation;
// Signal the rotation to start
progress = 0;
}
void Update()
{
if (progress < 1)
{
// If a rotation is occurring, increment the progress according to time
progress += Time.deltaTime;
// Then, use the progress to determine the container's current rotation
dummy.transform.rotation = Quaternion.Lerp(startRotation, targetRotation, progress);
}
}
注意:如果月亮自轉太快(目前將在約1秒內完成自轉),則只需增加一點即可使每一幀progress
,例如。 除以一個因子。
只要容器位於行星的中心,月亮就應始終保持與地面的恆定距離,並且通過這種方法將始終相對於行星表面保持一致的“向上”方向。
希望這可以幫助! 如果您有任何疑問,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.