在Unity中实现3D物理指南针(处理旋转)

4

在Unity中寻求旋转方面的帮助,我有一个手持3D指南针,手指向“北”是一个空的变换。我试图锁定手的旋转,这样当指南针倾斜时,手仍然准确地朝向北方。

问题是,当倾斜时手会从指南针中弹出。

以下是我目前拥有的代码和问题的图片。

public Transform target;
public Transform housing;
public float speed = 1.0f;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    var lookPos = target.position - transform.position; // assumes this script is attached to the needle
    var housingLocal = housing.InverseTransformPoint(lookPos); // change of coordinates from world space to housing space
    var localProjection = new Vector3(housingLocal.x, 0, housingLocal.z); // Remove the vertical offset so that we will look along the plane of the housing
    var worldProjection = housing.TransformPoint(localProjection); // change of coordinates back into world space

    var rotation = Quaternion.LookRotation(worldProjection);
    transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * speed);
}

enter image description here

1个回答

0
手本身的变换没问题吧?无论如何,我假设手的transform.up向量与手对齐(就像Unity中的圆柱体原型一样,您可以使用一个空对象作为父对象来修复此问题)。
在这种情况下,这段代码应该可以工作:
void Update()
{
    Vector3 lookPos = target.position - transform.position;
    transform.up = Vector3.Slerp(transform.up, lookPos, Time.deltaTime * speed);
}

有了这个,你的指南针手柄将始终平稳地指向北极点。如果不是必须使用四元数,我建议你避免使用它们,我总是更喜欢通过变换正交向量(右、上、前)进行旋转。


是的,手本身与外壳正确对齐。我还尝试使用空游戏对象进行偏移。这是目前在op中更新的代码... @Windgate - Calloom
你用我的代码有什么结果?如果你能分享一张手选的截图就太棒了。 - Windgate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接