微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关于OnTriggerStay和Input.GetKeyDown

如何解决关于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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。