Unity - 带旋转的 Sin & Cos 圆周运动
Unity - Sin & Cos circular motion with rotation
我正在尝试计算围绕物体的圆周运动(轨道)。我的代码给了我一个围绕物体的漂亮的圆形轨道。问题是当我旋转物体时,轨道的行为就好像物体没有旋转一样。
我在下面放了一个非常简单的图表来尝试更好地解释它。左边是我在圆柱体直立时得到的,中间是我当前在旋转物体时得到的。右边的图像是我想要发生的。
float Gx = target.transform.position.x - ((Mathf.Cos(currentTvalue)) * (radius));
float Gz = target.transform.position.z - ((Mathf.Sin(currentTvalue)) * (radius));
float Gy = target.transform.position.y;
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(new Vector3(Gx, Gy, Gz), 0.03f);
如何让轨道随着物体的旋转而变化?我试过将轨道位置 "new Vector3(Gx,Gy,Gz)" 乘以物体的旋转:
Gizmos.DrawWireSphere(target.transform.rotation*new Vector3(Gx, Gy, Gz), 0.03f);
但这似乎没有任何作用?
发生这种情况是因为您正在计算 world space 坐标 中的向量 (Gx, Gy, Gz),其中 target
对象的旋转是不考虑。
解决您需求的一种方法是使用target
对象的局部space坐标计算这个旋转,然后将它们转换为世界space坐标。这将使您的计算正确地考虑 target
对象的旋转。
float Gx = target.transform.localPosition.x - ((Mathf.Cos(currentTvalue)) * (radius));
float Gz = target.transform.localPosition.z - ((Mathf.Sin(currentTvalue)) * (radius));
float Gy = target.transform.localPosition.y;
Vector3 worldSpacePoint = target.transform.TransformPoint(Gx, Gy, Gz);
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(worldSpacePoint, 0.03f);
请注意,我没有使用 target.transform.position
检索给定变换的 world space 坐标 ,而是使用 target.transform.localPosition
,它检索给定变换的局部space坐标。
此外,我正在调用 TransformPoint() 方法,它将我在 local space 中计算的坐标转换为 [=] 中的相应值28=]世界space.
然后您可以安全地调用 Gizmos.DrawWireSphere()
方法,这需要世界 space 坐标才能正常工作。
我正在尝试计算围绕物体的圆周运动(轨道)。我的代码给了我一个围绕物体的漂亮的圆形轨道。问题是当我旋转物体时,轨道的行为就好像物体没有旋转一样。
我在下面放了一个非常简单的图表来尝试更好地解释它。左边是我在圆柱体直立时得到的,中间是我当前在旋转物体时得到的。右边的图像是我想要发生的。
float Gx = target.transform.position.x - ((Mathf.Cos(currentTvalue)) * (radius));
float Gz = target.transform.position.z - ((Mathf.Sin(currentTvalue)) * (radius));
float Gy = target.transform.position.y;
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(new Vector3(Gx, Gy, Gz), 0.03f);
如何让轨道随着物体的旋转而变化?我试过将轨道位置 "new Vector3(Gx,Gy,Gz)" 乘以物体的旋转:
Gizmos.DrawWireSphere(target.transform.rotation*new Vector3(Gx, Gy, Gz), 0.03f);
但这似乎没有任何作用?
发生这种情况是因为您正在计算 world space 坐标 中的向量 (Gx, Gy, Gz),其中 target
对象的旋转是不考虑。
解决您需求的一种方法是使用target
对象的局部space坐标计算这个旋转,然后将它们转换为世界space坐标。这将使您的计算正确地考虑 target
对象的旋转。
float Gx = target.transform.localPosition.x - ((Mathf.Cos(currentTvalue)) * (radius));
float Gz = target.transform.localPosition.z - ((Mathf.Sin(currentTvalue)) * (radius));
float Gy = target.transform.localPosition.y;
Vector3 worldSpacePoint = target.transform.TransformPoint(Gx, Gy, Gz);
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(worldSpacePoint, 0.03f);
请注意,我没有使用 target.transform.position
检索给定变换的 world space 坐标 ,而是使用 target.transform.localPosition
,它检索给定变换的局部space坐标。
此外,我正在调用 TransformPoint() 方法,它将我在 local space 中计算的坐标转换为 [=] 中的相应值28=]世界space.
然后您可以安全地调用 Gizmos.DrawWireSphere()
方法,这需要世界 space 坐标才能正常工作。