Quaternion.LookRotation()无法正常工作

时间:2019-06-28 13:45:01

标签: c# unity3d

我是Unity的新手,我尝试旋转箭头以指向特定的对象(在我的情况下,是屏幕截图中的左三角形)。我使用了lookRotation()函数,但不知道为什么它不能正常工作。这是一些屏幕截图。有什么建议吗?

public Transform target;

public Transform source;

public GameObject bigArrow;

void Start()
{

}

void Update()
{
    Vector3 direction = target.position - source.position;

    Quaternion rotation = Quaternion.LookRotation(direction);

    source.rotation = rotation;

    // ...
}

What I get when I run the application

If I change the position of the triangle the arrow rotate but not in the correct direction

Initial arrow direction

2 个答案:

答案 0 :(得分:0)

进一步评论以回答问题。

您要将箭头GameObject放在一个空的GameObject内,以便可以将其定向在世界坐标内以指向前方。

喜欢

Image of an arrow orientated towards the Z Axis

然后,您可以将Quaternion.LookRotation的箭头固定器以其向前的方向作为其指向的方向旋转。

答案 1 :(得分:0)

如果您不想将箭头包裹在一个空的游戏对象中,另一种解决方案是考虑箭头所指向的方向。

箭头指向Vector3.left的局部方向。您可以看出来,因为箭头的尖端与本地红色轴箭头相反。

因此,我们可以使用Quaternion.FromToRotation进行旋转,以将箭头的尖端(指向Vector3.left的方向)旋转到局部Vector3.forward的方向。然后,我们将LookRotation的结果乘以修改后的旋转,以生成我们感兴趣的旋转:

void Update()
{
    Vector3 direction = target.position - source.position;

    Quaternion rotation = Quaternion.LookRotation(direction);

    rotation *= Quaternion.FromToRotation(Vector3.left, Vector3.forward);

    source.rotation = rotation;

    // ...
}
相关问题