Unity 3D - Limit Camera Rotation

2020-05-06 13:53发布

问题:

I have found several awnsers to this question online, and I have tried all of them, but they either break my camera, or just overall don't work.

Here is my script:

using UnityEngine;
using System.Collections;

public class fp : MonoBehaviour
{

public float speedH = 2.0f;
public float speedV = 2.0f;

private float yaw = 0.0f;
private float pitch = 0.0f;

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

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

As far as I know, there is 3 solutions to this problem, but I don't know how to implement any of the solutions

Solution 1: Convert the script above to Unityscript (I have little expirience with C#) and I can solve the problem with "if" statements.

Solution 2: Provide the C# code to limit the angle on my script to an angle of 90 degrees all axis

Solution 3: All of the above

回答1:

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);


回答2:

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);
}