Maj*_*ajs 1 c# unity-game-engine unity5
我有一个 NPC,当玩家对撞机与 NPC 碰撞时,我的玩家可以与之交谈,我使用这段代码来做到这一点:
private void OnTriggerStay2D(Collider2D other)
{
if (other.gameObject.tag == "InteractiveArea")
{
if (Input.GetKeyDown(KeyCode.E))
{
Debug.Log("PRESSED NPC");
CreateAndShowDialog();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这真的是随机调用的,有时是我第一次按“E”,有时是第二次或第三次,等等。
我的刚体:
我使用的碰撞器是标准的 BoxCollider2D,我的玩家碰撞器是触发器,NPC 不是。
为什么在OnTriggerStay功能中没有检测到某些按键?
OnTriggerStay2D被随机调用。这就是为什么你永远不应该检查它里面的 Input 的原因。
设置为一个标志,true并false在OnTriggerEnter2D与OnTriggerExit2D函数然后检查在该标志和输入Update被称为每帧的功能。此外,始终使用CompareTag代替other.gameObject.tag来比较标签。
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;
}
}
Run Code Online (Sandbox Code Playgroud)