【问题标题】:if statement not executing in c# unity [closed]如果语句未在 C# Unity 中执行 [关闭]
【发布时间】:2020-04-20 15:22:49
【问题描述】:

我试图让一个角色移动一定距离,然后在他们移动一定距离时改变方向......我的代码中的逻辑可能是错误的我仍然需要处理这不是问题,问题是我的 if 语句没有执行

public class EnemyControl : MonoBehaviour
{
    private int xMoveDirection=-1;
    private float x;
    void Start()
    {
        x=gameObject.transform.position.x;
    }
    void Update()
    {
        gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(xMoveDirection,0);
        if(x==0.00){
          Debug.Log("helloimhere");
          xMoveDirection=0;
          x=x+1;
        }

【问题讨论】:

  • 此时x 的值多少?你能在“if”之前添加Debug.Log($"x = {x}")之类的东西吗?
  • @DougDawson Debug 的 if 语句之前的 x 值显示为 4.13
  • 但是如果你说x4.13 那么你为什么期望if 语句会执行呢?

标签: c# unity3d game-physics


【解决方案1】:

任何与浮点值的直接比较很可能会失败,您最好定义一个“足够接近”的值范围,例如Math.Abs(x) &lt; 0.0001

【讨论】:

  • 这个我试过了,if语句还是不运行
  • 您应该使用if(x &lt;= 0),因为即使定义了一个范围,对象也不太可能在某个帧精确定位在该范围内......您可能会过冲!
猜你喜欢
  • 2022-12-16
  • 2022-12-05
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
相关资源
最近更新 更多