如何使 2D 碰撞体在关卡开始之前不对已经碰撞的对象执行任何功能



在我的关卡中,我有一个水碰撞器,如果你掉进去,它会触发飞溅效果和水声。但是,由于水中已经有一个物体,每当我开始关卡时,水碰撞体都会触发,溅起水花和水声,尽管物体已经在对撞机中。

因此,即使物体深入水碰撞器内部,它也会产生飞溅声和水效果,就好像它刚刚掉进去一样。

我该如何防止这种情况?

我的代码涉及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());
}

你能发布你的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;
}

我希望它有所帮助!告诉我您是否需要更多内容,请发布您的代码,这样我们更容易确定问题在哪里并了解如何解决它。

祝你好运^^

最新更新