[英]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.