Unity3D C# 中的 OnTriggerEnter 碰撞体

0 c# unity-game-engine

我对 OnTriggerEnter 的工作原理或 Unity 中的碰撞体的工作原理感到非常困惑。我正在尝试添加一个碰撞测试,如果子弹击中一个物体,它会播放粒子系统并调试某些东西,但它不起作用,我很困惑为什么。请帮助。

这是我的代码:

公共类bulletScript: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);
}
Run Code Online (Sandbox Code Playgroud)

}

小智 5

碰撞器一开始可能有点棘手,但让我向您解释一下基础知识。

首先,接收任何类似OnCollisionEnter或的函数OnTriggerExit这些函数的游戏对象),必须附加一个 Collider 组件(您想要的任何形状的 2D 或 3D,具体取决于您的项目)。

然后,如果您想使用触发器,则必须选中碰撞器组件上的“是触发器”复选框。除此之外,一个或两个碰撞对象必须具有刚体

最后你肯定想查看Unity Collider手册的底部,其中包含Unity的碰撞矩阵,描述什么可以或不可以与什么碰撞。

此外,为了帮助您发展编码技能,我建议您在OnTriggerEnter函数中使用一些循环以保持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
    }
}
Run Code Online (Sandbox Code Playgroud)

希望有帮助;)