调用OnTriggerStay()时检查按键 [英] Check key press when OnTriggerStay() is called

查看:586
本文介绍了调用OnTriggerStay()时检查按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NPC,当玩家对撞机与NPC碰撞时,我的玩家可以与之交谈,我可以使用以下代码来做到这一点:

I have an NPC that my player can talk to when the players collider is colliding with the NPC, I do that using this piece of code:

private void OnTriggerStay2D(Collider2D other)
{
    if (other.gameObject.tag == "InteractiveArea")
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            Debug.Log("PRESSED NPC");
            CreateAndShowDialog();
        }
    }
}

但是,这实际上是随机调用的,有时是我第一次按"E",有时是第二次或第三次,等等.

However, this gets called really randomly, sometimes the first time I press "E", sometimes the second or third time, etc.

我的僵尸:

我使用的对撞机是标准BoxCollider2D,我的玩家对撞机是触发器,而NPC不是.

The colliders I use are standard BoxCollider2D, my players collider is a trigger, the NPCs is not.

为什么在OnTriggerStay功能中未检测到某些按键?

Why are some key press not detected in the OnTriggerStay function?

推荐答案

OnTriggerStay2D被随机调用.这就是为什么您永远不要检查其内部的Input的原因.

OnTriggerStay2D is called randomly. This is why you should never check for Input inside of it.

OnTriggerEnter2DOnTriggerExit2D函数中设置为truefalse的标志,然后检查该标志并输入Update函数(每帧).另外,请始终使用CompareTag而不是other.gameObject.tag来比较标签.

Set to a flag to true and false in the OnTriggerEnter2D and OnTriggerExit2D functions then check for that flag and input in the Update function which is called every frame. Also, always use CompareTag instead of other.gameObject.tag to compare tags.

private void Update()
{
    if (Input.GetKeyDown(KeyCode.E) && triggerStay)
    {
        //
    }
}

bool triggerStay = false;

void OnTriggerEnter2D(Collider2D collision)
{
    Debug.Log("Entered");
    if (collision.gameObject.CompareTag("InteractiveArea"))
    {
        triggerStay = true;
    }
}

void OnTriggerExit2D(Collider2D collision)
{
    Debug.Log("Exited");
    if (collision.gameObject.CompareTag("InteractiveArea"))
    {
        triggerStay = false;
    }
}

这篇关于调用OnTriggerStay()时检查按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆