首页 > 解决方案 > Unity Door open with "e"?

问题描述

I would like to be able to open my Gate with "e". I've got to the point where the player has to stand in front of the Gate and then you have to press "e", but I don't know how to do it. So far I've written that

private void OnTriggerEnter(Collider other) 
{
    if(other.CompareTag("Player") && Input.GetKeyDown("e"))
    {
        Debug.Log("door opens");
    }
}

}

标签: unity3d

解决方案


由于OnTriggerEnter仅称为玩家与门碰撞的单帧,因此请使用OnTriggerStay. 另一种选择是存储您是否与门发生碰撞,然后检测输入Update

如果您使用OnTriggerStay

private void OnTriggerStay(Collider other) 
{
    if(other.CompareTag("Player") && Input.GetKeyDown("e"))
    {
        Debug.Log("door opens");
    }
}

如果您想使用OnTriggerEnter静止,我也会使用OnTriggerExit知道它们何时不再与它发生碰撞。

private bool touchingDoor = false;

private void OnTriggerEnter(Collider other) 
{
    if(other.CompareTag("Player"))
    {
        touchingDoor = true;
    }
}

private void OnTriggerExit(Collider other) 
{
    if(other.CompareTag("Player"))
    {
        touchingDoor = false;
    }
}

private void Update()
{
    if(Input.GetKeyDown("e") && touchingDoor)
    {
        Debug.Log("door opens");   
    }
}

推荐阅读