需要帮助夹紧相机旋转

Need help clamping camera rotation

我对编码真的很陌生,并编写了这段代码来围绕播放器对象旋转我的相机,但我不知道如何继续将旋转固定在 X 轴上。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowPlayer : MonoBehaviour
{
    public float speed;
    public Transform target;

    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        transform.RotateAround(target.position, transform.right, -Input.GetAxis("Mouse Y") * speed);
        transform.RotateAround(target.position, Vector3.up, -Input.GetAxis("Mouse X") * speed);
    }
}

这是我旋转相机的代码,我想夹住Mouse Y一个。

这里的技巧是在进行转换之前跟踪累积的输入并对其进行限制。这比尝试将相机的旋转分解为正确的轴更容易 error-prone。

public class FollowPlayer : MonoBehaviour
{
    public float speed;
    public Transform target;

    float vertical;
    float horizontal;
    Quaternion initalRotation;
    Vector3 initialOffset;

    // Start is called before the first frame update
    void Start()
    {
        initialRotation = transform.rotation;
        initialOffset = transform.position - target.position;
    }
    // Update is called once per frame
    void Update()
    {
        horizontal += - Input.GetAxis("Mouse X") * speed;
        vertical += - Input.GetAxis("Mouse Y") * speed;
        vertical = Mathf.Clamp(vertical, -20f, 20f);

        //always rotate from same origin
        transform.rotation = initialRotation;
        transform.position = target.position + initialOffset;
        transform.RotateAround(target.position, transform.right, vertical);
        transform.RotateAround(target.position, Vector3.up, horizontal);
    }
}