FPS相机具有y轴限制到一定角度

时间:2017-02-21 06:15:22

标签: c# unity3d

我正在开始一个新游戏,现在我的玩家可以查看360 *但是我想限制玩家在天空中向下看的距离(向上和向下)。 这是我的代码

Vector2 mouseLook;
Vector2 smoothV;

public float sensitivity = 5.0f;
public float smoothing = 2.0f;

GameObject player;

void Start () {
    player = this.transform.parent.gameObject;
}

// Update is called once per frame
void Update () {
    var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

    md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
    smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
    smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
    mouseLook += smoothV;

    transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
    player.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, player.transform.up);
}

}

1 个答案:

答案 0 :(得分:2)

您必须使用Mathf.Clamp来执行此操作。以下是我用来向上/向下和向左/向右旋转相机的内容。您可以将yMaxLimityMinLimit变量修改为您要将其限制为的角度。在x方向移动时应该没有限制。

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

public float yMaxLimit = 45.0f;
public float yMinLimit = -45.0f;


float yRotCounter = 0.0f;
float xRotCounter = 0.0f;

Transform player;

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

// Update is called once per frame
void Update()
{
    xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime;
    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);
}