关于OnTriggerStay和Input.GetKeyDown

问题描述

直接讲到这一点,我在这代码上遇到了一些麻烦。 看来,一旦我按下interactableKey(“ E”)并且InputGetKeyDown返回true,OnTriggerStayMethod的大约6次执行就保持为true,因为它们没有同步,所以它破坏了我的代码

预期的行为: 当isHiding为false且语句1执行时,播放器按“ E”,因此isHiding设置为true。 当isHiding为true并且执行语句2时,玩家按下“ E”,因此isHiding设置为false。

实际行为: 当isHiding为false时,播放器按“ E”,语句1执行并将isHiding设置为true,然后紧接着又执行语句2,因为isHiding设置为true,并且Input.GetKeyDown的返回值显然仍然为true一些OnTriggerStay执行框架。破坏了我的代码

这是代码

 private void OnTriggerStay()
    {   
        //Statement 1
        if (Input.GetKeyDown(interactableKey) && this.isLocker && !PlayerManager.Instance.isHiding)
        {
            PlayerManager.Instance.currentHidingSpot = this.gameObject;
            PlayerManager.Instance.PerformHide();//This sets isHiding to true
            return; // This should be preventing the next if statement from being evaluated
        }
        //Statement 2
        if (Input.GetKeyDown(interactableKey) && this.isLocker && PlayerManager.Instance.isHiding)
        {
            PlayerManager.Instance.PerformExitHide(); //This sets isHiding to false
        }
    }

很抱歉,这是否令人困惑,我通常不在这里提问,但我从未遇到过像这样的问题。让我知道你的想法。

解决方法

每个Unity Frame可以多次调用OnTriggerStay方法。它在物理时钟周期而不是帧周期上运行。因此,您不会在这里使用Input.GetKeyDown,因为GetKeyDown在最后一帧中向下引用了键。

相反,尝试读取Update方法中的输入,然后在OnTriggerStay方法中执行如下操作:

private bool allowInteraction;

private void Update ( )
{
    if ( Input.GetKeyDown ( interactableKey ) )
        allowInteraction = true;
}

private void OnTriggerStay ( )
{
    if ( allowInteraction && isLocker )
    {
        if ( PlayerManager.Instance.isHiding )
        {
            //Statement 2
            PlayerManager.Instance.PerformExitHide ( ); //This sets isHiding to false
        }
        else
        {
            //Statement 1
            PlayerManager.Instance.currentHidingSpot = this.gameObject;
            PlayerManager.Instance.PerformHide ( );//This sets isHiding to true
        }
    }
    allowInteraction = false;
}