[英]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.