void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Wall")
{
Destroy(gameObject);
}
}
我使用这个脚本。一切正常,但如果我的 bullet
在 Wall
中生成,它不会与墙发生 react 。它在墙内飞行。
那么,如果子弹在墙内生成,我应该使用什么来立即摧毁子弹?
子弹生成方法:
Instantiate(bullet1, firepoint1.position, firepoint1.rotation);
最佳答案
因为当 GameObject 在另一个碰撞器中实例化时,碰撞器会带来麻烦。我建议你首先检查子弹是否会在墙内实例化,如果是这种情况,直接不实例化它。我相信这将使代码更有效率。
所以首先您需要在层中添加墙(Here 您可以看到如何创建一个新层并将墙分配给该层)。将其作为参数传递给用于实例化子弹的脚本(例如坦克的脚本)。
public LayerMask wallLayer;
您将坦克的变换保存在一个变量中
// Variable with position of the Tank
Transform _transform;
void Awake () {
_transform = GetComponent<Transform> ();
}
接下来生成 Physics2D.Linecast
。 Source .假设您使用附加到坦克游戏对象的脚本来发射子弹:
// Linecase goes from the tank position to the place where you would be instantiating the bullet
boolean insideWall = Physics2D.Linecast(_transform.position, firepoint1.position, wallLayer);
然后实例化子弹,以防万一您不会在墙内实例化它。
if(!insideWall)
Instantiate(bullet1, firepoint1.position, firepoint1.rotation);
关于c# - 子弹在墙内实例化,不会触发 OnCollisionEnter2D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56190680/