【问题标题】:OnTriggerEnter Colliders In Unity3D C#Unity3D C# 中的 OnTriggerEnter 碰撞器
【发布时间】:2022-01-21 06:02:43
【问题描述】:

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

这是我的代码:

public class 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);
}

}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

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

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

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

    最后你肯定想检查Unity Collider manual的底部,它包含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
        }
    }
    

    希望有所帮助;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      相关资源
      最近更新 更多