我正在尝试制作FPS控制器,但遇到了问题。相机旋转得很好,但是我可以向X
方向旋转并倒过来。我尝试使用Mathf.Clamp
,但无法正常使用。这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PJCamera : MonoBehaviour {
Vector2 mouseLook;
Vector2 smoothV;
public float sensibilidad = 5;
public float smooth = 2;
GameObject Personaje;
// Use this for initialization
void Start () {
//Definimos quien es "personaje", el padre de la cámara.
Personaje = this.transform.parent.gameObject;
}
// Update is called once per frame
void Update () {
//Cuanto se esta moviendo el raton (md = mouseDelta)
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
//Multiplicamos los vectores, el de la posición por la sensibilidad
md = Vector2.Scale(md, new Vector2(sensibilidad * smooth, sensibilidad * smooth));
//PRUEBA
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smooth);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f /smooth);
mouseLook += smoothV;
//Hacemos que rote
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
Personaje.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, Personaje.transform.up);
}
}
答案 0 :(得分:0)
我想您正在尝试使照相机在上下移动时最大旋转,在这种情况下,您可以使用Angle(Vector3 from, Vector3 to);
,其中from是您的camera.forward向量,to是您的楼层。这里的示例:https://docs.unity3d.com/ScriptReference/Vector3.Angle.html
使用夹具的解决方案:
xRotation= Mathf.Clamp(xRotation, minRoation, maxRotation);
//of course use local variables here, i give you a loong line just to help you understand.
Camera.main.transform.localEulerAngles = new Vector3(xRotation, Camera.main.transform.localEulerAngles.y, Camera.main.transform.localEulerAngles.localEulerAngles.z);
通常,如果要限制旋转,则应在2个旋转之间插入transform.rotation:minRotation和maxRotation。这是来自统一文档的示例:https://docs.unity3d.com/ScriptReference/Quaternion.Slerp.html