【问题标题】:Mathf.clamp is not working correctlyMathf.clamp 工作不正常
【发布时间】:2014-07-19 04:20:39
【问题描述】:

我已经在 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); 

    }
}

如果你们中的任何人可以帮助我,那就太好了。谢谢。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您的倒置逻辑有缺陷,只需将其取出即可。要反转旋转,您只需要反转输入,而不是每帧的旋转本身(它只会从 + 变为 - 并再次返回 + 等等)。这是一个带有倒置标志的 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() 函数中获取相机的原始旋转。现在的方式是将第一帧的旋转设置为零。我无法从脚本中判断这是否是预期的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-23
      • 2023-04-10
      • 2015-01-16
      • 1970-01-01
      • 2016-08-02
      • 2020-02-18
      • 2013-01-22
      • 1970-01-01
      相关资源
      最近更新 更多