【问题标题】:Trigger Collinder doesnt work with Input.GetKey触发器对撞机不适用于 Input.GetKey
【发布时间】:2020-06-30 09:24:26
【问题描述】:

我正在尝试制作一个可以砍树的游戏,但是当我测试我的脚本时它根本不起作用。此脚本用于砍伐树木。当我将 TakeDmg 和 Destroytree 放在私有 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

【问题讨论】:

    标签: unity3d 2d collider


    【解决方案1】:

    您的代码将要求用户已经按住 E(或在同一帧中)击中树。

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


    你应该使用OnTriggerStay2D

    发送每个帧,其中另一个对象位于附加到该对象的触发对撞机中(仅限 2D 物理)。

    只要您在触发器内,就可以监听 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);
        }
    }
    

    【讨论】:

    • 我是否需要一个盒子对撞机并在播放器上触发它才能工作?
    • 当我添加动画时它工作了,非常感谢你,我昨天站了两三个小时来解决这个问题
    • 我还有一个小问题,我应该在代码中添加一个计时器,如何添加它,我对编码有点陌生
    • 您应该在 Inspector 中调整 cutInterval .. 即计时器(参见下面的第二个解决方案)
    • 但我将您的第一个建议用于私人 void OnTriggerStay2D(Collider2D other),bcz 我希望玩家向 e 键发送垃圾邮件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2016-01-17
    • 1970-01-01
    • 2020-04-24
    • 2014-05-14
    相关资源
    最近更新 更多