【问题标题】:Strange If/Else Behavior奇怪的 If/Else 行为
【发布时间】:2015-08-10 05:51:22
【问题描述】:

上下文

我正在制作一款要求玩家按指定顺序触摸对象的手机游戏。正确的顺序在名为 clickOrder 的列表中确定。要确定玩家应该点击的当前对象,使用 currClickIndex。

问题

当触摸一个正确的对象时,调试文本会在瞬间显示“正确”,然后立即变为“错误”。我不确定的是为什么 if 和 else 块都在只接触一个对象时执行。

代码

void Update()
{
    if (Input.touchCount == 1)
    {
        if (this.enabled)
        {
            Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero);

            if (hit != null && hit.collider != null)
            {
                // check if the touched object is the correct one
                if (hit.collider.gameObject == clickOrder[MyData.currClickIndex])
                {
                    debug.text = "Correct";
                    MyData.currClickIndex++;
                }
                else
                {
                    debug.text = "Wrong";
                }
            }
        }
    }
}

【问题讨论】:

  • 你查看过日志历史吗?它应该在它之后立即显示“正确”和“错误”。如果是这样的话,你能想出一种可能发生的方式吗?如果这就是你的情况发生的方式吗?提示:每秒会调用很多次更新。
  • 奇怪的是,只要触摸到对象,就会显示“正确”。但是,只要对象仍被触摸,这将立即转变为连续的多个“错误”实例。
  • MyData.currClickIndex++;告诉你什么?
  • 还有一点:if (this.enabled) 是多余的。如果 MonoBehaviour 被禁用,则永远不会调用 Update()if (this.enabled) 在你的情况下永远不会失败。

标签: unity3d


【解决方案1】:

只要触摸到正确的对象,您就可以这样做:

MyData.currClickIndex++;

它使你按顺序向前移动,从那时起,以前正确的对象不再正确。但你还在摸它。

如果您想避免这种情况,您需要按触摸到正确的对象后的顺序向前移动。

if (there are touches and the correct object is being touched)
{
      set a flag;
}
else if (a flag has been set)
{
      MyData.currClickIndex++;
      reset the flag;
}

【讨论】:

  • 我明白了!在我最初的方法中,当我不应该这样做时,我在序列中前进,但是通过使用标志,我现在能够正确控制序列。非常感谢!
  • 或者,您可以仅在触摸开始时按顺序前进,而不是每次更新,而且这不需要标志。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 2011-07-21
  • 2013-11-16
  • 1970-01-01
相关资源
最近更新 更多