繁体   English   中英

如何限制相机的垂直旋转 Unity 3D

[英]How to limit camera's vertical rotation Unity 3D

我想限制相机的垂直旋转,使其无法进行 360 度旋转。 我已经尝试了很多教程,但没有任何对我有用,所以我。

还请检查我的代码。

[RequireComponent(typeof(PlayerMoto))]

public class PlayerController: MonoBehaviour {

  public float speed = 5, sensetivity;
  private PlayerMoto motor;
  public GameObject hands;
  public camera cam;
  float lookUpMax = .6 f;

  void Start() {
    motor = GetComponent < PlayerMoto > ();
    cam = GetComponent < camera > ();
  }

  void Update() {
    //cam.transform.localEulerAngles = new Vector3(cam.transform.localEulerAngles.x, 0, 0);
    float _xmove = Input.GetAxis("Horizontal");
    float _zmove = Input.GetAxis("Vertical");
    Vector3 _moveHorizontal = transform.right * _xmove;
    Vector3 _movVertical = transform.forward * _zmove;
    Vector3 _velocity = (_moveHorizontal + _movVertical) * speed;
    motor.Move(_velocity);
    float _yRot = Input.GetAxis("Mouse X");
    Vector3 _rotation = new Vector3(0 f, _yRot, 0 f) * sensetivity;
    motor.Rotate(_rotation);
    float _xRot = Input.GetAxis("Mouse Y");
    Vector3 _cameraRotation = new Vector3(_xRot, 0 f, 0 f) * sensetivity;
    motor.RotateCamera(_cameraRotation);
    if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.W)) {
      for (; speed <= 15; speed++) {
        speed = 15;
      }
    } else {
      speed = 10;
    }
  }
}

非常感谢您的帮助。 我真的很感谢每一条评论,试图帮助我完成这个奇妙的旅程。

试试这个

 private void Rotation()
    {
        x_axis += speed * Input.GetAxis("Mouse X"); // speed = 2f;

        y_axis -= speed * Input.GetAxis("Mouse Y");
        y_axis = Mathf.Clamp (y_axis, -45, 45); // limits vertical rotation

        transform.eulerAngles = new Vector3(y_axis, x_axis, 0.0f);
    }

如果我理解你的代码,移动相机的部分是:

float _xRot = Input.GetAxis("Mouse Y");
Vector3 _cameraRotation = new Vector3(_xRot, 0f, 0f) * sensetivity;

然后,您的代码在另一个类上调用此方法

motor.RotateCamera(_cameraRotation);

这可能(因为之前的建议不起作用)应用轮换通过

GameObject.Rotate(_cameraRotation);

为了限制你的相机的旋转,我们需要直接应用旋转,如果通过在现有旋转上添加一个旋转来应用旋转,它不能被钳制。 因此,假设您可以跳过该调用并直接应用旋转(我不知道是否会有副作用),并且假设您的cam变量是您的相机。 如果所有这些假设都是正确的,您可以尝试:

float _xRot += Input.GetAxis("Mouse Y") * sensetivity;
xRot = Mathf.Clamp(_xRot, xMin, xMax);
cam.transform.rotation = Quaternion.Euler(_xRot, 0.0f, 0.0f);

记得注释掉

//motor.RotateCamera(_cameraRotation);

你可以声明

public float xMin;
public float xMax;

并尝试使用值,直到找到最佳值。

我强烈怀疑我建议的代码不能解决您的所有问题,或者它可能会增加问题,因为您的播放器和相机的实际转换是由另一个脚本应用的,但未提供。 在这种情况下,您也可以向我们提供该代码,但我建议您尝试编写自己的代码,您可以根据需要对其进行自定义。

至于为什么夹紧旋转并不像看起来那么容易,这篇文章很有趣: 旋转、四元数和欧拉角

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM