【问题标题】:Unity3D How to constrain rotation without rigidbody?Unity3D如何在没有刚体的情况下约束旋转?
【发布时间】:2019-04-29 04:50:29
【问题描述】:

我正在制作一个脚本,它应该像操纵杆一样旋转游戏对象,这意味着只有 X 轴和 Z 轴必须改变。所以我使用 sin 和 cos 函数来计算旋转角度。但由于某种原因,Y 轴也发生了变化。

public float alpha;

void Update () {
        alpha += Time.deltaTime;

        var x = R * Mathf.Cos(alpha);
        var z = R * Mathf.Sin(alpha);
        transform.Rotate(new Vector3(x, 0, z) * Time.deltaTime);
    }

所以问题是如何阻止 Y 轴发生变化,或者也许还有另一种方法可以像操纵杆一样旋转对象。

附:我正在使用 Unity 2017.4.13f1

【问题讨论】:

  • 我不是 Unity 用户,但我并不完全理解您的代码。什么是 R(半径?旋转矩阵?)为什么要将旋转向量乘以增量时间,而不是目标角度?
  • deltaTime 用于非常平滑地增加角度,R 是增加旋转角度的乘数。它只是一个浮点数。

标签: c# unity3d


【解决方案1】:

我决定每帧都将 Y 轴设置为 0。也许不是最优雅的解决方案,但它可以满足我的需要。

Vector3 rotationVector;

void Start()
{
    rotationVector = new Vector3();
}

private float alpha;
public float multiplier;

void Update () 
{
    alpha += Time.deltaTime;

    rotationVector.x = Mathf.Cos(alpha);
    rotationVector.z = Mathf.Sin(alpha);

    transform.Rotate(multiplier * rotationVector * Time.deltaTime);
    transform.eulerAngles = new Vector3(transform.eulerAngles.x, 0, transform.eulerAngles.z);
}

【讨论】:

    【解决方案2】:

    在你的更新函数中你可以写:

    public float alpha;
    public Vector3 rotation;
    void Start(){
        rotation = transform.rotation.eulerAngles;
    }
    
    void Update () {
        alpha += Time.deltaTime;
        var x = Mathf.Cos(alpha);
        var z = Mathf.Sin(alpha);
        rotation.x = x;
        rotation.z = z;
        transform.rotation = Quaternion.Euler(rotation*time.deltaTime);
    }
    

    我无法理解你乘以 Sin 和 Cos 的 R 变量。R 是在哪里定义的???

    【讨论】:

    • 您的代码有效,但移动不顺畅。 R变量是增加角度的乘数。我知道这是一个不好的命名,我打算稍后将其更改为更有意义的名称。
    • 如果你想要流畅的运动,你可以看看vector3.lerp。这是它的链接docs.unity3d.com/ScriptReference/Vector3.Lerp.html
    猜你喜欢
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多