- Home /
Checking 2DCollisions During a single Update
I have a weapon that launches a round and damage should only be dealt to enemies within it's Collider2D when it impacts the ground. What's the best way to deal with this? What I have now is as follows.
public virtual void Spawn()
{
gameObject.SetActive(true);
PlayerControls.Instance.PlaySound(audioFire);
isHitGround = false;
GetComponent<Collider2D>().enabled = false;
}
//called when the weapon hits the ground
protected virtual void HitGround()
{
if (!isHitGround)
{
isHitGround = true;
isSetToExpire = true;
GetComponent<Collider2D>().enabled = true;
renderer.enabled = false;
PlaySoundOnGround(audioHit);
}
}
//And in the update
protected override void Update ()
{
if (isSetToExpire)
{
isSetToExpire = false;
gameObject.SetActive(false);
return;
}
if(height <= 0)
{ HitGround(); }
}
//It should only check the OnTriggerEnter2D when the Collider2D is enabled.
protected virtual void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.CompareTag("Enemy"))
{
if (col.gameObject.GetComponent<EnemyBase>().isAlive)
{ col.gameObject.GetComponent<EnemyBase>().HitByBullet(damage); }
}
}
On Spawning the weapon, the Collider2D.enabled is set to false so that it doesn't check collisions while in the air. When it hits the ground, the Collider is enabled so that it can check OnTriggerEnter2D before going through it's update again and disabling itself to return to the available weapon pool.
For the most part, this seems to work but it randomly doesn't for one out of say 10 shots.
My theory on why this is that it's due to both the weapons AND enemies being recycled from a pool. So when the weapon's Collider2D is disabled, it retains the collisions it had up to that point and those collisions haven't exited. So if the same bullet's Collider2D turns on upon impact and encounters the same recycled enemy.Collider2D, it counts it as a OnTriggerStay2D rather than an OnTriggerEntry2D. If this is the case, does anyone know how to cleanse the weapon's Collider2D on spawn?
Alternatively, is there a better way to do what I'm trying to do here? Maybe I'm overcomplicating things.
Your answer
Follow this Question
Related Questions
Mario-Like Enemy Death System Not Working 1 Answer
OnTriggerEnter2D Not Working 1 Answer
Trying to spawn enemies 1 Answer
Enemy not taking damage on collisions. 2 Answers
Enemy collision with wall, destroys wall 2 Answers