Mathf.clamp无法正常工作

时间:2014-07-18 17:54:01

标签: c# unity3d

我在Unity中创造了自己的角色,我现在正在使用相机,我想要锁定相机的Y旋转,而我正在以正确的方式进行此操作。

mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f);

所以刚刚发生的事情是相机从359旋转到0.在玩游戏时我移动鼠标之前没有任何反应。它使屏幕看起来像闪烁。

这是我的完整代码:

using UnityEngine;
using System.Collections;

public class FirstPersonController : MonoBehaviour {

    CharacterController cc;

    public float baseSpeed = 3.0f;
    public float mouseSensitivity = 1.0f;

    float mouseRotX = 0,
          mouseRotY = 0;

    public bool inverted = false;

    float curSpeed = 3.0f;

    string h = "Horizontal";
    string v = "Vertical";

    void Start () {
        cc = gameObject.GetComponent<CharacterController>();
    }

    void FixedUpdate () {

        curSpeed = baseSpeed;

        mouseRotX = Input.GetAxis("Mouse X") * mouseSensitivity;
        mouseRotY -= Input.GetAxis("Mouse Y") * mouseSensitivity;;
        mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f);
        if (!inverted)
            mouseRotY *= -1;
        else
            mouseRotY *= 1;

        float forwardMovement = Input.GetAxis(v);
        float strafeMovement = Input.GetAxis(h);

        Vector3 speed = new Vector3(strafeMovement * curSpeed, 0, forwardMovement * curSpeed);
        speed = transform.rotation * speed;



        cc.SimpleMove(speed);
        transform.Rotate(0, mouseRotX, 0);
        Camera.main.transform.localRotation = Quaternion.Euler(mouseRotY, 0 ,0); 

    }
}

如果你们中的任何人能够帮助我,那将是非常棒的。感谢。

1 个答案:

答案 0 :(得分:0)

你倒置的逻辑是有缺陷的,只要拿出它就可以了。要反转旋转,您需要每帧只反转输入而不是旋转本身(它将从+到 - 然后再返回到+,依此类推)。这是一个带有反转标志的y旋转的精简版本:

using UnityEngine;
using System.Collections;

public class FirstPersonController : MonoBehaviour 
{
    public float mouseSensitivity = 1.0f;

    float mouseRotY = 0.0f;

    public bool inverted = false;
    private float invertedCorrection = 1.0f;

    void FixedUpdate ()
    {
        if(Input.GetAxis ("Fire1") > 0.0f)
            inverted = !inverted;

        if(inverted)
            invertedCorrection = -1.0f;
        else
            invertedCorrection = 1.0f;

        mouseRotY -=  invertedCorrection * Input.GetAxis("Mouse Y") * mouseSensitivity;

        mouseRotY = Mathf.Clamp(mouseRotY, -90.0f, 90.0f);

        Camera.main.transform.localRotation = Quaternion.Euler(mouseRotY, 0.0f, 0.0f); 
    }
}

您可能想要做的另一件事是在Start()函数中获取相机的原始旋转。它现在的方式是在第一帧上将旋转设置为零。我不能从脚本中判断这是否是预期的行为。