Unity 3D - Limit Camera Rotation

大兔子大兔子 提交于 2019-12-02 09:25:56

You don't post what you've tried, so this is a shot in the dark on helping you. Check Unity's Mathf.Clamp to restrict the angles allowed.

yaw += speedH * Input.GetAxis("Mouse X");
pitch -= speedV * Input.GetAxis("Mouse Y");

yaw = Mathf.Clamp(yaw, -90f, 90f);
pitch = Mathf.Clamp(pitch, -60f, 90f);

transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
Programmer

There is no attempt to limit any axis in your code. Use a temporary variable to limit your axis by incrementing it each tome Input.GetAxis changes. If it reaches the min or max value you want to limit it to then the Mathf.Clamp to clamp it between that min and max values/angle.

Modified this to limit your FPS camera in both axis instead of usual y-axis limit.

public float xMoveThreshold = 1000.0f;
public float yMoveThreshold = 1000.0f;

//Y limit
public float yMaxLimit = 45.0f;
public float yMinLimit = -45.0f;
float yRotCounter = 0.0f;

//X limit
public float xMaxLimit = 45.0f;
public float xMinLimit = -45.0f;
float xRotCounter = 0.0f;

Transform player;

void Start()
{
    player = Camera.main.transform;
}

// Update is called once per frame
void Update()
{
    //Get X value and limit it
    xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime;
    xRotCounter = Mathf.Clamp(xRotCounter, xMinLimit, xMaxLimit);

    //Get Y value and limit it
    yRotCounter += Input.GetAxis("Mouse Y") * yMoveThreshold * Time.deltaTime;
    yRotCounter = Mathf.Clamp(yRotCounter, yMinLimit, yMaxLimit);
    //xRotCounter = xRotCounter % 360;//Optional
    player.localEulerAngles = new Vector3(-yRotCounter, xRotCounter, 0);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!