Mathf.Clamp 和 Unity 中的旋转问题

Problem with Mathf.Clamp and rotation in Unity

我的相机移动有问题。我想限制我的相机旋转,但我不知道该怎么做。我搜索了解决方案,但找不到。

在我当前的代码中,我的相机在任何方向快速旋转,我不知道如何正确实现 Mathf.Clamp。

这是我的代码:

public float rightSpeed = 20.0f;
public float leftSpeed = -20.0f;
public float rotationLimit = 0.0f;

void Update()
{
    //EdgeScrolling
    float edgeSize = 40f;
    if (Input.mousePosition.x > Screen.width - edgeSize)
    {
        //EdgeRight
        transform.RotateAround(this.transform.position, Vector3.up, rotationLimit += rightSpeed * Time.deltaTime);
    }

    if (Input.mousePosition.x < edgeSize)
    {
        //EdgeLeft
        transform.RotateAround(this.transform.position, Vector3.up, rotationLimit -= leftSpeed * Time.deltaTime);
    }

    rotationLimit = Mathf.Clamp(rotationLimit, 50f, 130f);
}

RotateAround 方法旋转 一个角度。它不会分配您传递给它的角度值。在这种情况下,我建议使用不同的方法。而不是 RotateAround 方法使用 eulerAngles 属性 并直接分配旋转值。

示例

using UnityEngine;

public class TestScript : MonoBehaviour
{
    public float rightSpeed = 20.0f;
    public float leftSpeed = -20.0f;

    private void Update()
    {
        float edgeSize = 40f;
        
        if (Input.mousePosition.x > Screen.width - edgeSize)
            RotateByY(rightSpeed * Time.deltaTime);
        else if (Input.mousePosition.x < edgeSize)
            RotateByY(leftSpeed * Time.deltaTime);
    }

    public void RotateByY(float angle)
    {
        float newAngle = transform.eulerAngles.y + angle;

        transform.eulerAngles = new Vector3(
            transform.eulerAngles.x,
            Mathf.Clamp(newAngle, 50f, 130f),
            transform.eulerAngles.z);
    }
}