【问题标题】:How to fix negative magnitude in 2D Unity project如何修复 2D Unity 项目中的负幅值
【发布时间】:2019-06-28 13:57:24
【问题描述】:

我在 Unity 中构建了一个简单的 2D 项目并尝试实现运动学物理。我的移动向量量级为负,我想知道为什么。

对撞机就在墙的边缘,但我不明白它究竟是如何影响私有变量的

FixedUpdate 中调用的 Move 方法

private void Move(Vector2 destination)
{
    // destination: "(0.0, -0.1)"

    float distance = destination.magnitude;
    // destination: "(0.0, -0.1)"   distance: -0.00999999978

    if (distance > MinMoveDistance)
    {
        int count = rigidbody2D.Cast(destination, hitBuffer, distance + ShellRadius);

        for (int i = 0; i < count; i++) 
        {
            Vector2 currentNormal = hitBuffer[i].normal;

            if (Mathf.Approximately(currentNormal.y, 1f)) 
            {
                IsGrounded = true;
            }

            float modifiedDistance = hitBuffer[i].distance - ShellRadius;

            distance = modifiedDistance < distance ? modifiedDistance : distance;
        }
    }

    rigidbody2D.position = rigidbody2D.position + destination.normalized * distance;
}

【问题讨论】:

  • 您在代码中的哪一点检查distance 的值?如果您在分配它之后立即检查它,那么它不可能是负值。我怀疑您稍后会检查它(很可能之后它通过modifiedDistance 代码块下方更改)。
  • 很明显距离不是负数,因为你要进入if (distance &gt; MinMoveDistance) 块。你没有准确地描述情况。

标签: c# unity3d vector game-physics


【解决方案1】:

float distance = destination.magnitude; 应该始终返回一个正数,不确定您是如何获得在 cmets 中提供的值。

无论如何,如果要确保distance 始终为正,只需使用 float distance = Mathf.Abs(destination.magnitude);

【讨论】:

  • float distance = Mathf.Abs(destination.magnitude); 返回相同的结果,但类似 ​​float a = distance; a = Mathf.Abs(a); // a: 0.00999999978 奇怪的东西
猜你喜欢
  • 1970-01-01
  • 2021-12-18
  • 2020-11-08
  • 1970-01-01
  • 2018-03-13
  • 2012-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多