unity3d 将四元数旋转固定为单位

llew8vvj  于 2023-01-31  发布在  其他
关注(0)|答案(2)|浏览(161)

我有这个代码,但我一直无法找到一个体面的解决方案,以钳之间的2个Angular 值的X轴。它将如何在这种情况下完成?

public class CameraController : MonoBehaviour {
    public float cameraSmoothness = 5f;

    private Quaternion targetGlobalRotation;
    private Quaternion targetLocalRotation = Quaternion.Identity;

    private void Start(){
        targetGlobalRotation = transform.rotation;
    }

    private void Update(){
        targetGlobalRotation *= Quaternion.Euler(
            Vector3.up * Input.GetAxis("Mouse X"));
        
        targetLocalRotation *= Quaternion.Euler(
            Vector3.right * -Input.GetAxis("Mouse Y"));

        transform.rotation = Quaternion.Lerp(
            transform.rotation,
            targetGlobalRotation * targetLocalRotation,
            cameraSmoothness * Time.deltaTime);
    }
}
igetnqfo

igetnqfo1#

为此,您宁愿使用欧拉角,并仅在应用夹具后将其转换为Quaternion

永远不要直接触摸Quaternion的单个组件,除非你真的知道你在做什么!Quaternion四个组件xyzw,它们都在-11的范围内移动,所以你的尝试没有什么意义;)

可能是这样的。

// Adjust via Inspector
public float minXRotation = 10;
public float maxXRotation = 90;

// Also adjust via Inspector
public Vector2 sensitivity = Vector2.one;

private float targetYRotation;
private float targetXRotation;

private void Update()
{
    targetYRotation += Input.GetAxis("Mouse X")) * sensitivity.x;      
    targetXRotation -= Input.GetAxis("Mouse Y")) * sensitivity.y;

    targetXRotation = Mathf.Clamp(targetXRotation, minXRotation, maxXRotation);

    var targetRotation = Quaternion.Euler(Vector3.up * targetYRotation) * Quaternion.Euler(Vector3.right * targetXRotation);

    transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, cameraSmoothness * Time.deltaTime);
}
c90pui9n

c90pui9n2#

你需要像这样夹住鼠标Y + transform.rotation.x

float v = Input.GetAxis("Mouse Y") * -_verticalSensitive;
    float x = _camera.transform.rotation.x;
    float r = Mathf.Clamp(x + v, -0.5f, 0.5f) - x;
    _camera.transform.Rotate(r, 0, 0);

相关问题