【问题标题】:Continuously rotating by 90 doesn't get me the initial angle连续旋转 90 度无法获得初始角度
【发布时间】:2020-05-06 00:56:23
【问题描述】:

我有一个游戏对象每两秒旋转 90 度,使该对象的 Z 旋转有 4 个可能的值。由于初始 Z 旋转为 45,因此其他值将是 135、225 和 315。 每次游戏对象旋转时,它都会在字典中查找其当前的 Z 旋转:

static public Dictionary<int, string> rotDirection = new Dictionary<int, string>{
        {45, "NE"},
        {135, "SE"},
        {225, "SW"},
        {315, "NW"},
    };

但是,它没有找到初始值 (45),因为它在旋转中得到的实际上是 44。为什么会发生这种情况?

float timer;
    void FixedUpdate()
    {
        timer -= Time.deltaTime;
        if (timer <= 0.0f)
        {
            timer += Constants.cannonRotationTime;

            //transform's initial (z) rotation is 45
            transform.Rotate(0.0f, 0.0f, 90);
            int angle = (int)transform.rotation.eulerAngles.z;
            Debug.Log("Angle: " + angle + ", direction: " +
            (Constants.rotDirection.ContainsKey(angle) ?
                Constants.rotDirection[angle] : "*NOT FOUND*"));
        }

还有一件奇怪的事情。如果我将游戏对象的初始 (Z) 旋转设置为 135,则所有值都会被找到,它会旋转到 45 而不是 44:

现在,如果我将其设置为 225 或 315,则没有新的旋转有意义,这就是我得到的:

为什么会发生这种情况,我该如何避免?

【问题讨论】:

    标签: unity3d rotation euler-angles


    【解决方案1】:

    还有一个专门的函数可以舍入到整数,而无需强制转换:

    Mathf.RoundToInt(float var)

    int angle = Mathf.RoundToInt(transform.rotation.eulerAngles.z)
    

    【讨论】:

    • 这成功了。但是,我仍然想知道为什么会出现这个问题。谢谢。
    【解决方案2】:

    您的代码对我来说很好用。也许这里正在进行一些时髦的 float 到 int 的转换?

    即 44.99999° 变为 44。

    int angle = (int)transform.rotation.eulerAngles.z;
    

    你能Debug.Log把它转换成整数之前的角度吗?

    【讨论】:

      【解决方案3】:

      它的圆形问题:你可以使用Mathf.Round

      int angle = (int)Mathf.Round(transform.rotation.eulerAngles.z);
      

      【讨论】:

        猜你喜欢
        • 2018-03-21
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 2011-03-22
        • 1970-01-01
        • 1970-01-01
        • 2014-07-11
        • 2015-03-22
        相关资源
        最近更新 更多