为什么Input.GetMouseButtonDown不能让我射击?

问题描述

当SemiAuto为false时,Update函数中的“我的代码”有效,但为true时,它不会射击

        if (canShoot && !Grapple) { 
            canShoot = false;
            StartCoroutine(Shoottimer());
            if (semiauto && Input.GetMouseButtonDown(0)){
                    shoot.Shoot();
            }
            if (Input.GetMouseButton(0) && !semiauto){
                shoot.Shoot();
            }
        }

我知道Shoot.Shoot()可以工作,因为当semiauto为true时,它可以正常工作,并且它在Update中而不是FixedUpdate中,所以这不是问题。

解决方法

您的代码检查2条不同的路径(可能不是故意的?):

根据您的描述,有效的路径会检查:

如果semiautofalse并且Input.GetMouseButton(0)是真实的然后射击

..但路径无效,请检查:

如果semiautotrue并且Input.GetMouseButtonDown(0)是真实的然后射击

注意区别吗?一个呼叫Input.GetMouseButton(0),而另一个呼叫Input.GetMouseButtonDown(0)。由于其他所有内容都相同,因此我怀疑第一个调用返回true,而第二个调用返回false,从而导致if语句主体无法执行。

那么,如何解决这个问题?如果我了解您要正确执行的操作,则可以使用以下英语逻辑:

如果IF模式为semiauto,则每次点击拍摄一次;否则,只要按住鼠标按钮即可射击。

考虑到这一点,我们可以引入bool来了解我们是否处于拍摄模式。您有一个canShoot,但不确定是否将其用于其他用途。因此,在您的bool canShoot旁边(类范围,而不是函数范围),添加:bool isShooting = false;

现在,在您的更新中,无论何时按下或释放鼠标按钮,我们都需要打开和关闭拍摄模式:

if(Input.GetMouseButtonDown(0))
{
   // Mouse button is pressed - enter shooting mode
   isShootingMode = true;
}
else if(Input.GetMouseButtonUp(0))
{
   // Mouse button released - exit shooting mode
   isShootingMode = false;
}

上面的代码现在可以控制我们是否处于拍摄模式。现在进入semiauto部分,也进入Update

if(isShootingMode)
{
   shoot.Shoot(); // we know we're in shooting mode,so shoot!
   if(semiauto)
   {
      // If we're in semi-auto mode,exit shooting mode,as we already shot once
      isShootingMode = false;
   }
}

就是这样!只需将其与您的其余逻辑集成即可。