📜  unity 如何旋转某个东西以指向其他东西 - C# (1)

📅  最后修改于: 2023-12-03 14:48:12.635000             🧑  作者: Mango

Unity 如何旋转某个东西以指向其他东西 - C#

在 Unity 中,我们可以使用 Quaternion 和 Vector3 来旋转和定位物体。

旋转物体指向其他物体

要使一个物体朝向另一个物体,我们可以使用以下代码:

public Transform targetObject;

void Update()
{
    Vector3 direction = targetObject.position - transform.position;
    Quaternion rotation = Quaternion.LookRotation(direction);
    transform.rotation = rotation;
}

这段代码使用 transform.LookAt() 方法来使物体朝向另一个物体。我们首先计算物体与目标物体之间的方向向量 direction,然后使用 Quaternion.LookRotation() 方法将其转换为旋转,最后将该旋转应用于物体的 transform.rotation 属性。

旋转物体的方向

我们也可以使用 Quaternion.Euler()Quaternion.AngleAxis() 来旋转物体的方向。

使用 Quaternion.Euler()
void Update()
{
    float rotateSpeed = 50.0f;
    float rotationAmount = rotateSpeed * Time.deltaTime;
    float horizontalInput = Input.GetAxis("Horizontal");

    Quaternion rotation = Quaternion.Euler(0, horizontalInput * rotationAmount, 0);
    transform.rotation = transform.rotation * rotation;
}

这段代码使物体根据玩家的水平输入逆时针或顺时针旋转。

我们使用 Quaternion.Euler() 方法来创建一个旋转,其中第一个参数为水平旋转量,即绕 Y 轴旋转的角度。我们然后将该旋转应用于物体的 transform.rotation 属性。

使用 Quaternion.AngleAxis()
void Update()
{
    float rotateSpeed = 50.0f;
    float rotationAmount = rotateSpeed * Time.deltaTime;
    float horizontalInput = Input.GetAxis("Horizontal");

    Vector3 rotateAxis = Vector3.up;
    Quaternion rotation = Quaternion.AngleAxis(horizontalInput * rotationAmount, rotateAxis);
    transform.rotation = transform.rotation * rotation;
}

这段代码与上面的相似,只是使用了 Quaternion.AngleAxis() 方法来创建旋转。我们提供了两个参数,一个是旋转角度,一个是旋转轴。在这种情况下,我们使用了 Unity 中的内置向量 Vector3.up 作为旋转轴。

结论

本教程演示了在 Unity 中旋转物体以朝向其他物体和旋转物体的方向。这是一些常见的旋转操作,需要知道如何掌握它们以创建令人惊叹的场景和游戏。

参考链接:https://docs.unity3d.com/ScriptReference/Quaternion.html