c# - 子弹在墙内实例化,不会触发 OnCollisionEnter2D

标签 c# unity3d

void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Wall")
        {
            Destroy(gameObject);
        }
    }

我使用这个脚本。一切正常,但如果我的 bullet Wall 中生成,它不会与墙发生 react 。它在墙内飞行。 那么,如果子弹墙内生成,我应该使用什么来立即摧毁子弹?

子弹生成方法:

Instantiate(bullet1, firepoint1.position, firepoint1.rotation);

enter image description here

最佳答案

因为当 GameObject 在另一个碰撞器中实例化时,碰撞器会带来麻烦。我建议你首先检查子弹是否会在墙内实例化,如果是这种情况,直接不实例化它。我相信这将使代码更有效率。

所以首先您需要在层中添加墙(Here 您可以看到如何创建一个新层并将墙分配给该层)。将其作为参数传递给用于实例化子弹的脚本(例如坦克的脚本)。

public LayerMask wallLayer;

您将坦克的变换保存在一个变量中

// Variable with position of the Tank
Transform _transform;

void Awake () {

    _transform = GetComponent<Transform> ();

}

接下来生成 Physics2D.LinecastSource .假设您使用附加到坦克游戏对象的脚本来发射子弹:

// 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/

相关文章:

C# 防止DataGridView离开

c# - 避免 XML 转义双引号

c# - 由于其保护级别而无法访问结构

Unity3D,从Unity.UI面板构建PNG吗?

c# - 统一: Trying to send command for object without authority error when more than one client is connected

c# - 如何为 NHibernate 创建内部映射类?

c# - C# 中的多键字典(另一种)?

c# - SQL:保存 MIME 类型或扩展名?

c# - Unity中的简单事件系统

c# - 如何使用 Microsoft Scene Understanding SDK 和 hololens2 将 Unity 场景与玩家的物理房间对齐?