如何让 2D 碰撞体在关卡开始前不对已经发生碰撞的物体执行任何操作

How do I make the 2D collider not do any function to already colliding objects before level start

在我的关卡中,我有一个水对撞机,如果你掉进去,它会触发飞溅效果和水声。但是,因为水中已经有一个物体,每当我开始关卡时,尽管物体已经在对撞机中,但水对撞机会触发并发出飞溅和水声。

因此,即使对象位于水对撞机的深处,它也会产生飞溅的声音和水效果,就好像它刚掉进去一样。

如何防止这种情况发生?

我的代码涉及 OnTrigger2D 函数。但是如何让 Unity 在关卡加载之前检查对象是否已经发生碰撞?

代码:

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Player")
    {
            gravityoriginal = playerrigidbody.gravityScale;
        massoriginal = playerrigidbody.mass;
            playerrigidbody.gravityScale = 0.1f;
            playerrigidbody.mass = other.GetComponent<Rigidbody2D>().mass + 2f;
            splash.Play(); //Plays the initial splash if velocity is high
            underwaterbool.IsUnderwater = true; //stop dust particle
            mainmusic.enabled = true;
            powerupmusic.enabled = true;
            deathmusic.enabled = true;
    }
    else if (other.tag == "Snatcher")
    {
        masssnatcheroriginal = snatcherrigidbody.mass;
            gravityoriginalsnatcher = snatcherrigidbody.gravityScale;
            snatcherrigidbody.gravityScale = 0.1f;
            snatcherrigidbody.mass = other.GetComponent<Rigidbody2D>().mass + 2f;
            splashsnatcher.Play();
            snatchersounds.enabled = true;
    }
    else if (other.tag != "Player" && other.tag != "Snatcher" && other.GetComponent<Rigidbody2D>() != null)
    {
            gravityoriginalbox = other.GetComponent<Rigidbody2D>().gravityScale;
            massoriginalbox = other.GetComponent<Rigidbody2D>().mass;
            other.GetComponent<Rigidbody2D>().mass = other.GetComponent<Rigidbody2D>().mass + 2f;
            other.GetComponent<Rigidbody2D>().gravityScale = 0.1f;
            other.GetComponent<ParticleSystem>().Play(false);
            splashaudio.Play();
            Splashparticlesforbox.IsUnderwaterBox = true;
    }
    if(other.GetComponent<Rigidbody2D>() != null)
    {
        other.GetComponent<Rigidbody2D>().velocity = new Vector2(0f, -0.5f);
    }
    if (!cooldown)
    {
        splashaudio.Play();
    }
    cooldown = true;
    StartCoroutine(waittime());
}

你能post你的OnTrigger2D函数代码吗?通常情况下,如果场景开始时对象已经在触发器内,Unity 不会触发 OnTriggerEnter 方法,但每帧都会执行 OnTriggerStay。

无论如何...一种选择(我认为不是最好的选择)是在初始化为 true 的触发器中放置一个布尔属性,并使用它来防止 OnTriggerFunctions 做任何事情,直到成名结束。然后在 LateUpdate 方法中,您可以将 属性 设置为 false.

bool m_FirstFrame = true;

void onEnable()
{
   m_FirstFrame = true;
}

void OnTriggerEnter2D(Collider2D collision)
{
        if(m_FirstFrame){
            return;
        }
        .... //Rest of code
}

//Same for the other OnTrigger2D methods you use

void LateUpdate()
{
   m_FirstFrame = false;
}

希望对您有所帮助!如果您需要更多信息,请告诉我,post 您的代码,这样我们可以更轻松地找到问题出在哪里并找到解决方法。

祝你好运^^