触发器对撞机不适用于 Input.GetKey

Trigger Collinder doesnt work with Input.GetKey

我正在尝试制作一款可以砍树的游戏,但是当我测试我的脚本时它根本不起作用。该脚本用于砍伐树木。当我将 TakeDmg 和 Destroytree 放在 private void OnTriggerEnter2D(Collider2D other) 中时,它工作正常,但是当我添加 if(Input.GetKey(KeyCode.E)) 时,它停止工作我真的不知道那是问题。

public int treeHp;
public GameObject logPrefab;
public Animator anim;


private void OnTriggerEnter2D(Collider2D other){

    if(Input.GetKey(KeyCode.E)){

        TakeDmg();
        Destroytree();
    }
}
public void TakeDmg(){
    anim.SetTrigger("TreeDamage");    
    treeHp = treeHp -1;
}

public void Destroytree(){

    if(treeHp <= 0){
        //spawn la loguri 

        Destroy(gameObject);
    }
}

谢谢:D

您的代码将要求用户在 E(或在同一帧)撞树。

我希望你先靠近树然后然后按E来砍树。


你应该使用 OnTriggerStay2D

Sent each frame where another object is within a trigger collider attached to this object (2D physics only).

以便只要您在触发器内即可收听 E 键。然后我也会使用 Input.GetKeyDown 来只处理一次而不是每一帧。

否则你会做

anim.SetTrigger("TreeDamage");    
treeHp = treeHp -1;

在打孔 E 时的每一帧,这是 A) 帧率依赖和 B) 可能不是你想在这里做的。

public float cooldownDuration;
private bool coolDown;

// Listen for the key as long as you stay in the collider
private void OnTriggerStay2D(Collider2D other)
{
    if(!coolDown && Input.GetKeyDown(KeyCode.E))
    {
        TakeDmg();
        Destroytree();

        StartCoroutine(CoolDown());
    }
}

IEnumerator CoolDown()
{
    coolDown = true;

    yield return new WaitForSeconds(cooldownDuration);

    coolDown = false;
}

如果你真的想在按住 E 的同时继续切割,你可以这样做

// Adjust in the Inspector: Seconds to wait before next cut
public float cutInterval = 1f;
private bool colliderExitted;

// Listen for the key as long as you stay in the collider
private void OnTriggerStay2D(Collider2D other)
{
    if(Input.GetKeyDown(KeyCode.E))
    {
        StartCoroutine(CuttingRoutine())
    }
}

private void OnTriggerExit2D(Collider2D other)
{
    colliderExitted = true;
}

private IEnumerator CuttingRoutine()
{
    colliderExitted = false;
    while(!colliderExitted && Input.GetKey(KeyCode.E))
    {
        anim.SetTrigger("TreeDamage");    
        treeHp = treeHp -1;

        // Add a delay before the next iteration
        yield return new WaitForSeconds(cutInterval);
    }
}