- Home /
How to reliably break contact/collision?
I'm making a top down game in a style similar to the original Legend of Zelda. I wanna put in a mechanic that would prevent enemies from getting the player stuck in a corner.
The idea is to upon contact disable collisions between player and enemies for a brief period. The code I have can prevent future collisions between player and enemy, but it doesn't disable the triggering collision.
Basically for as long as the player and the enemy are touching each other they remain corporeal to each other. Any advice on how to reliably break a specific collision or break contact? Or maybe design better around this issue?
Relevant player code:
public void ApplyDmg(int dmg){
if(!isImmune)
HP -= dmg;
if (HP <= 0)
gameObject.SetActive (false);
else
StartCoroutine(PlayerImmunity (immunityDuration, 0.2F));
}
IEnumerator PlayerImmunity(float duration, float blinkTime) {
isImmune = true;
float immunityTime = Time.time + duration;
Physics2D.IgnoreLayerCollision (playerLayerID, enemyLayerID);
while (immunityTime > Time.time) {
//toggle renderer
renderer.enabled = !renderer.enabled;
//wait for a bit
yield return new WaitForSeconds(blinkTime);
}
//make sure renderer is enabled when we exit
renderer.enabled = true;
Physics2D.IgnoreLayerCollision (playerLayerID, enemyLayerID, false);
isImmune = false;
}
Relevant enemy code:
void OnCollisionEnter2D(Collision2D other){
if (!isStunned && other.gameObject.tag == "Player"){
other.gameObject.SendMessage ("ApplyDmg", 1);
ApplyStun(0.3F); //Applies a brief stun to itself
Debug.Log ("Register hit Player");
}
}
Does your Enemy or Player have RigidBody? If Yes does some of them, have a child object, that is assigned to different Layer (Like Default) and have a Collider Component?
Yes, both of them have a RigidBody2D component.
Yes, Player object does have a couple of child objects assigned to Default layer. Namely the AttackColliders, they each consist of a Transform and a BoxCollider2D components, all of which are triggers. They are used for hit detection. The BoxCollider2D components remain disabled by default, being enabled upon attack for exactly 1 frame to detect collisions.
I just tried changing those to the Player layer, but the issue still remains the same. Besides, doing that would mean that player immunity also disables player attacks, would it not?
Usually if you have a gameObject with RigidBody and child with colliders, Unity is considering those as Compound Colliders. That coud be the reason, why you are still registering the trigger, between the Player and Enemies.
Other than that, if the collision is turned Off, when you IgnoreLayerCollision, there shoud be no trigger registered between these 2 colliders. (If i understood correctly, this is what happens in your case, Collision is Ignored, but you still get a trigger registration)...
Try debugging, what's the name of the object that's getting triggered...