首页 > 解决方案 > unity 添加单轴旋转

问题描述

美好的一天,将单轴添加到旋转时遇到问题。我有一个外部方法,可以在平面上设置 2d 旋转,绑定到玩家角色。但它不能使用 Y 轴,因此武器旋转仅限于 xz 平面。暴露的方法有一个旋转的 queterion 条目,我正在努力向它添加一个垂直部分。

protected virtual void RotateWeapon(Quaternion newRotation)
    {
        if (GameManager.Instance.Paused)
        {
            return;
        }

        RaycastHit hit;
        Physics.Raycast(_reticlePosition, Vector3.down * 1000, out hit);
        Debug.DrawLine(_reticlePosition, hit.point, Color.red);
        //Hit.point.z is a vertical part i need to add to newRotation

        // if the rotation speed is == 0, we have instant rotation
        if (WeaponRotationSpeed == 0)
        {
            transform.rotation = newRotation;
        }
        // otherwise we lerp the rotation
        else
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, WeaponRotationSpeed * Time.deltaTime);
        }

标签: c#unity3d

解决方案


Quaternions您可以通过将两者与*运算符相乘来添加旋转,例如

newRotation *= additionalRotation;

然后为了生成,additionalRotation您可以使用Quaternion.Euler并传入一个Vector3表示旋转拆分为每个轴的欧拉角分量的值。

我没有完全理解你的用例,但如果你想旋转,例如只围绕 Z 轴,你会做

newRotation *= Quaternion.Euler(Vector3.forward * angle);

或者,如果您更愿意采用给定Quaternion但将其限制为仅在 Z 等某个轴上旋转,您可以使用

newRotation =  Quaternion.Euler(Vector3.Scale(Vector3.forward, newRotation.euerAngles));

您可以将 替换为Vector3.forward任何其他向量,指示应该使用哪些轴角度,例如new Vector3(1,0,1)保持 X 和 Z 旋转但消除 Y 旋转(请参阅Vector3.Scale


推荐阅读