簡體   English   中英

OnTrigger 在 Unity3D C# 中輸入對撞機

[英]OnTriggerEnter Colliders In Unity3D C#

我對 OnTriggerEnter 的工作方式或 Unity 中的 Colliders 的工作方式感到非常困惑。 我正在嘗試添加一個碰撞測試,如果子彈擊中 object,它會播放一個粒子系統並調試一些東西,但它不起作用,我很困惑為什么。 請幫忙。

這是我的代碼:

公共 class 子彈腳本:MonoBehaviour {

public ParticleSystem explosion;

public float speed = 20f;
public Rigidbody rb;

bool canDieSoon;

public float timeToDie;

void Start()
{
    canDieSoon = true;
}
// Start is called before the first frame update
void Update()
{

    rb.velocity = transform.forward * speed;

    if(canDieSoon == true)
    {
        Invoke(nameof(killBullet), timeToDie);
        canDieSoon = false;
    }
    


}



private void OnTriggerEnter(Collider collision)
{

    if (collision.gameObject.tag == "ground")
    {
        Debug.Log("hit ground");
        explosion.Play();
    }
    if (collision.gameObject.tag == "robot")
    {
        Debug.Log("hit ground");
        explosion.Play();
    }
    if (collision.gameObject.tag == "gameObjects")
    {
        Debug.Log("hit ground");
        explosion.Play();
    }
    if (collision.gameObject.tag == "walls")
    {
        Debug.Log("hit ground");
        explosion.Play();
    }
    if (collision.gameObject.tag == "doors")
    {
        Debug.Log("hit ground");
        explosion.Play();
    }
}




void killBullet()
{
    Destroy(gameObject);
}

}

對撞機在開始時可能會有點棘手,但讓我向您解釋一下基礎知識。

首先,要接收任何 function (如OnCollisionEnterOnTriggerExit游戲對象,其中將調用那些 function 必須獲得一個 Collider 組件(2D 或 Z76AA96369ABBBA52E621BFA83DAE 取決於您的項目中的任何形狀)。

然后,如果您想使用觸發器,則必須選中對撞機組件上的“是觸發器”復選框。 除此之外,碰撞的 object 之一或兩者必須具有剛體

最后你一定要查看Unity Collider 手冊的底部,其中包含 Unity 的碰撞矩陣,描述了什么可以或不能與什么碰撞。

此外,為了幫助您提高編碼技能,我建議您在OnTriggerEnter function 中使用一些循環以保持DRY

private void OnTriggerEnter(Collider collision)
{
    string[] tagToFind = new string[]{"ground", "robot", "gameObjects", "walls", "doors"};

    for(int i = 0; i < tagToFind.Length; i++)
    {
        var testedTag = tagToFind[i];
        //compareTag() is more efficient than comparing a string
        if (!collision.CompareTag(testedTag)) continue; //return early pattern, if not the good tag, stop there and check the others
        
        Debug.Log($"hit {testedTag}"); //improve your debug informations
        explosion.Play();
        return; //if the tag is found, no need to continue looping
    }
}

希望有幫助;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM