OnTrigger在Unity3D C#中输入碰撞器



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

这是我的代码:

公共类bulletScript:MonoBehavior{

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

}

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

首先,要接收任何像OnCollisionEnterOnTriggerExit这样的函数,调用这些函数的gameObject必须附加一个对撞机组件(根据您的项目,可以是2D或3D的任何形状(。

然后,如果你想使用触发器,你必须检查";是触发器";碰撞器组件上的复选框。除此之外,碰撞物体中的一个或两个必须具有刚体

最后,你可以查看Unity对撞机手册的底部,其中包含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
}
}

希望有所帮助;(

最新更新